假设我有一个数组如下:
$food['fruit'] = array('apples','oranges','bananas');
$food['veg'] = array('potatoes','onions','peppers');
$food['meat'] = array('bacon','beef','chicken');
如何订购,以便将任何给定类型的食物带到阵列的顶部,其余的订单保持不变?
因此,如果用户选择“veg”,则会将订单更改为:
$food = array('veg' => ..., 'fruit' => ..., 'meat' => ...);
答案 0 :(得分:1)
$tmp_val = array('key'=>$food['key']);
unset($food['key']);
array_unshift($food,$tmp_val)
答案 1 :(得分:1)
您可以创建一个新阵列,重新排列并替换旧阵列:
$first = 'veg';
$tmp = array ($first => $food[$first]);
foreach ($food AS $key => $val) {
if ($key != $first) {
$tmp[$key] = $val;
}
}
$food = $tmp;
或
$first = 'veg';
$tmp = array ($first => $food[$first]);
unset ($food[$first]);
$food = array_merge ($tmp, $food);
答案 2 :(得分:1)
$food = array_merge(array('veg' => $food['veg']), $food);
但整件事看起来很可疑。你能解释一下为什么需要这个吗?
答案 3 :(得分:0)
这不是一种排序,因为你只想移动一个元素,所以:
array_splice()
从阵列中间删除元素。array_unshift()
将其添加到数组的前面。答案 4 :(得分:0)
避免循环:
$food['fruit'] = array('apples','oranges','bananas');
$food['veg'] = array('potatoes','onions','peppers');
$food['meat'] = array('bacon','beef','chicken');
$food['fish'] = array('code','haddock','plaice');
$key = 'veg';
if (array_key_exists($key,$food)) {
$tmp[$key] = $food[$key];
array_splice($food,array_search($key,array_keys($food)),1);
$food = $tmp+$food;
}
echo '<pre>';
var_dump($food);
echo '</pre>';