对于ex有这个数组:
[food] => Array (
[fruits] => apple
[vegetables] => garlic
[nuts] => cashew
[meat] => beaf
)
Run Code Online (Sandbox Code Playgroud)
我需要更改特定键值组合的位置.
假设我需要将[fruits] => apple移到第3位
[food] => Array (
[vegetables] => garlic
[nuts] => cashew
[fruits] => apple
[meat] => beaf
)
Run Code Online (Sandbox Code Playgroud)
我不是在谈论按键或值排序.我需要将键值的位置改为非常严格的新位置.
就像是:
change_pos($my_arr, $key_to_move, $new_index);
Run Code Online (Sandbox Code Playgroud)
=>
change_pos($my_arr, "fruits", 3);
Run Code Online (Sandbox Code Playgroud)
那可能吗?
这很难,但最后:
<?php
function array_splice_assoc(&$input, $offset, $length, $replacement) {
$replacement = (array) $replacement;
$key_indices = array_flip(array_keys($input));
if (isset($input[$offset]) && is_string($offset)) {
$offset = $key_indices[$offset];
}
if (isset($input[$length]) && is_string($length)) {
$length = $key_indices[$length] - $offset;
}
$input = array_slice($input, 0, $offset, TRUE)
+ $replacement
+ array_slice($input, $offset + $length, NULL, TRUE);
}
function array_move($which, $where, $array)
{
$tmpWhich = $which;
$j=0;
$keys = array_keys($array);
for($i=0;$i<count($array);$i++)
{
if($keys[$i]==$tmpWhich)
$tmpWhich = $j;
else
$j++;
}
$tmp = array_splice($array, $tmpWhich, 1);
array_splice_assoc($array, $where, 0, $tmp);
return $array;
}
$array = array('fruits' => 'apple','vegetables' => 'garlic','nuts' => 'cashew','meat' => 'beaf');
$res = array_move('vegetables',2,$array);
var_dump($res);
?>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7869 次 |
| 最近记录: |