请你能帮助我:
我有一个按键排序的数组:
$a['a'] = value;
$a['b'] = value;
$a['c'] = value;
$a['d'] = value;
$a['e'] = value;
我需要通过这个规则重新定位 - 拿一个字段放在第一位,另一个不改变
f.e。
$a['c'] = value;
$a['a'] = value;
$a['b'] = value;
$a['d'] = value;
$a['e'] = value;
或
$a['d'] = value;
$a['a'] = value;
$a['b'] = value;
$a['c'] = value;
$a['e'] = value;
答案 0 :(得分:1)
我认为你的意思是这样的:
function get_and_place_first($index, $array) {
$new_first_element = $array[$index]; // save element you want to have as first
unset($array[$index]); // delete that element from old position
array_unshift($array, $new_first_element); // place it at the beginning of $array
}
您应该以这种方式使用它:
get_and_place_first('c', $a);
你应该从第一个例子中得到理想的效果。当然你可能想检查元素是否存在于给定的数组等中,但这取决于你。
答案 1 :(得分:0)
从http://ykyuen.wordpress.com/2011/09/16/php-swap-array-elements-by-array-keys/
尝试此功能function array_swap_assoc($key1, $key2, $array) {
$newArray = array ();
foreach ($array as $key => $value) {
if ($key == $key1) {
$newArray[$key2] = $array[$key2];
} elseif ($key == $key2) {
$newArray[$key1] = $array[$key1];
} else {
$newArray[$key] = $value;
}
}
return $newArray;
}
代码示例:
<?php
$temp = array('a' => 'A', 'b' => 'B');
$temp = array_swap_assoc('a', 'b', $temp);
print_r($temp);
?>