$arr = array(
'a' => 1,
'b' => 2,
'move me' => 9,
'c' => 3,
'd' => 4,
);
嘿,我想在 ['b'] 之前移动 ['move me']。我只需 4 行代码就可以做到!
$i = 0; foreach($arr as &$val) $val = array('sort' => (++$i * 10), 'val' => $val);
$arr['move me']['sort'] = $arr['b']['sort'] - 5;
uasort($arr, function($a, $b) { return $a['sort'] > $b['sort']; });
foreach($arr as &$val) $val = $val['val'];
我制作了一个易于使用的功能:
function move_item(&$ref_arr, $key1, $move, $key2 = null)
{
$arr = $ref_arr;
if($key2 == null) $key2 = $key1;
if(!isset($arr[$key1]) || !isset($arr[$key2])) return false;
$i = 0; foreach($arr as &$val) $val = array('sort' => (++$i * 10), 'val' => $val);
if(is_numeric($move))
{
if($move == 0 && $key1 == $key2) return true;
elseif($move == 0) { $tmp = $arr[$key1]['sort']; $arr[$key1]['sort'] = $arr[$key2]['sort']; $arr[$key2]['sort'] = $tmp; }
else $arr[$key1]['sort'] = $arr[$key2]['sort'] + ($move * 10 + ($key1 == $key2 ? ($move < 0 ? -5 : 5) : 0));
}
else
{
switch($move)
{
case 'up': $arr[$key1]['sort'] = $arr[$key2]['sort'] - ($key1 == $key2 ? 15 : 5); break;
case 'down': $arr[$key1]['sort'] = $arr[$key2]['sort'] + ($key1 == $key2 ? 15 : 5); break;
case 'top': $arr[$key1]['sort'] = 5; break;
case 'bottom': $arr[$key1]['sort'] = $i * 10 + 5; break;
default: return false;
}
}
uasort($arr, function($a, $b) { return $a['sort'] > $b['sort']; });
foreach($arr as &$val) $val = $val['val'];
$ref_arr = $arr;
return true;
}
例子:
move_item($arr, 'move me', 'up'); //move it one up
move_item($arr, 'move me', 'down'); //move it one down
move_item($arr, 'move me', 'top'); //move it to top
move_item($arr, 'move me', 'bottom'); //move it to bottom
move_item($arr, 'move me', -1); //move it one up
move_item($arr, 'move me', 1); //move it one down
move_item($arr, 'move me', 2); //move it two down
move_item($arr, 'move me', 'up', 'b'); //move it before ['b']
move_item($arr, 'move me', -1, 'b'); //move it before ['b']
move_item($arr, 'move me', 'down', 'b'); //move it after ['b']
move_item($arr, 'move me', 1, 'b'); //move it after ['b']
move_item($arr, 'move me', 2, 'b'); //move it two positions after ['b']
//Special syntax, to swap two elements:
move_item($arr, 'a', 0, 'd'); //Swap ['a'] with ['d']
我希望这可以帮助很多人,因为它是一个很棒的功能!:D