php - 用键前置数组值

时间:2021-08-26 22:08:42

I have an array. It looks like this

我有一个阵列。看起来像这样

$choices = array(
array('label' => 'test1','value' => 'test1'),
array('label' => 'test2','value' => 'test2'),
array('label' => 'test3','value' => 'test3'),
)

Now i would like to prepend this value in $choices array

现在我想在$ choices数组中添加这个值

array('label' => 'All','value' => 'all'),

It looks like I cannot use array_unshift function since my array has keys.

看起来我不能使用array_unshift函数,因为我的数组有键。

Can someone tell me how to prepend?

谁能告诉我如何前置?

1 个解决方案

#1


2  

Your $choices array has only numeric keys so array_unshift() would do exactly what you want.

你的$ choices数组只有数字键,所以array_unshift()会完全按照你的意愿行事。

$choices = array(
    array('label' => 'test1','value' => 'test1'),
    array('label' => 'test2','value' => 'test2'),
    array('label' => 'test3','value' => 'test3'),
);
echo $choices[0]['label']; // echoes 'test1'

$array_to_add = array('label' => 'All','value' => 'all');
array_unshift($choices, $array_to_add);

/* resulting array would look like this:
$choices = array(
    array('label' => 'All','value' => 'all')
    array('label' => 'test1','value' => 'test1'),
    array('label' => 'test2','value' => 'test2'),
    array('label' => 'test3','value' => 'test3'),
);
*/
echo $choices[0]['label']; // echoes 'All'

#1


2  

Your $choices array has only numeric keys so array_unshift() would do exactly what you want.

你的$ choices数组只有数字键,所以array_unshift()会完全按照你的意愿行事。

$choices = array(
    array('label' => 'test1','value' => 'test1'),
    array('label' => 'test2','value' => 'test2'),
    array('label' => 'test3','value' => 'test3'),
);
echo $choices[0]['label']; // echoes 'test1'

$array_to_add = array('label' => 'All','value' => 'all');
array_unshift($choices, $array_to_add);

/* resulting array would look like this:
$choices = array(
    array('label' => 'All','value' => 'all')
    array('label' => 'test1','value' => 'test1'),
    array('label' => 'test2','value' => 'test2'),
    array('label' => 'test3','value' => 'test3'),
);
*/
echo $choices[0]['label']; // echoes 'All'