我试图用jQuery UI(可排序)将表的顺序保存到
PHP数组中.
我已经非常简化了,但这是它的基本想法.我有一个表中嵌有可排序的列表.该表通过PHP foreach生成,涉及包含在另一个文件(config.PHP)中的多维数组.
config.PHP文件:
<?PHP
$config = array(
"mno" => array('item 5'),"abc" => array('item 1'),"ghi" => array('item 3'),"pqr" => array('item 6'),"jkl" => array('item 4'),"vwx" => array('item 8'),"def" => array('item 2'),"stu" => array('item 7'),);
?>
table(index.html):
<table cellpadding="2" cellspacing="0" align="center" id="mytable">
<tbody>
<?PHP
$i = 0;
include 'config.PHP';
foreach($config AS $name => $value){
$item = $value[0];
echo '
<tr id="'.$name.'-'.$i++.'">
<td>'.$item.'</td>
</tr>';
}
?>
</tbody> </table>
scripts(index.html):
<!-- Add jQuery library -->
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<!-- Add jQuery UI library -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var fixHelper = function(e,ui) {
ui.children().each(function() {
$(this).width($(this).width());
});
return ui;
};
$("#mytable tbody").sortable({
helper: fixHelper,opacity: 0.5,scroll: false,update: function () {
var data = $('#mytable tbody').sortable('serialize');
$.post("edit.PHP",{'neworder': data});
}
}).disableSelection();
});
</script>
排序工作正常,但我不知道如何将新的顺序值($_POST [‘neworder’])保存到数组中是什么在config.PHP中.
我想我必须用file_put_contents的组合使用uasort()(或uksort(),uksort())的PHP函数来保存config.PHP中的新命令.
所以这样的事情
<?PHP
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['neworder'])) {
/*
Here file_put_contents in config.PHP the new order. So:
$config = array(
"mno" => array('item 5'),);
Becomes:
$config = array(
"abc" => array('item 1'),"mno" => array('item 5'),);
After this is send by Jquery UI:
neworder:abc[]=1&def[]=6&ghi[]=2&jkl[]=4&mno[]=0&pqr[]=3&stu[]=7&vwx[]=5
I've tried this:
$filename = 'config.PHP';
$lines = file( $filename,FILE_IGnorE_NEW_LInes );
$linenumber = 2;
foreach( $_POST['neworder'] AS $name => $val){
$phost = $val[0];
$lines[$linenumber] = ' "'.$name.'" => array(\'' . $phost . '\'),';
$linenumber++;
}
file_put_contents( $filename,implode( "\n",$lines ) );
But the '$val' is not send with Jquery only the order.
*/
}
?>
解决方法
您将要使用带有关闭的usort(可在PHP 5.3中获取)以按需要的顺序获取密钥.
$newOrder = $_POST["neworder"];
$config_keys = array_keys($config);
usort($config_keys,function($a,$b) use($newOrder) {
return array_search($a,$newOrder) - array_search($b,$newOrder);
});
然后,您可以将$config重新写入新订单
$newConfig = array();
foreach($config_keys as $key){
$newConfig[$key] = $config[$key];
}
$config = $newConfig;
unset($newConfig);
从这里你可以坚持使用任何一种方法对于你的用例最有意义的$config.我建议不要使用它创建一个PHP文件,但更好的方法可能是使用
file_put_contents($cacheFile,serialize($config));
然后检索
$config = unserialize(file_get_contents($cacheFile));