如何在每个subArray的开头添加key => value元素?

时间:2022-04-12 21:48:10

So I recently got into this school project and now I have to deal with multidimensional arrays in PHP. My problem:

所以我最近进入了这个学校项目,现在我必须处理PHP中的多维数组。我的问题:

I have an array:

我有一个数组:

$arr = array(
           array('subject' => 'Deutsch'), 
           array('subject' => 'Deutsch'),  
           array('subject' => 'Deutsch')
       );

And now I want to make it look like:

现在我想让它看起来像:

array(
    array('id' => 1, 'subject' => 'Deutsch'),   
    array('id' => 2, 'subject' => 'Deutsch'),  
    array('id' => 3, 'subject' => 'Deutsch')
);  

I thought of doing something like:

我想做的事情如下:

foreach ($arr as $key => $value) {
    array_unshift($arr, array('id' => $key + 1));
}

But this doesn't give me the expected output. How can I modify my code to get to my goal?

但这并没有给我预期的输出。如何修改代码以实现目标?

2 个解决方案

#1


1  

You can array_merge() the id to each subArray, e.g.

你可以通过array_merge()将id添加到每个subArray,例如

foreach ($arr as $key => $value) {
    $arr[$key] = array_merge(["id" => $key + 1], $value);
}

#2


0  

You can itterate the array by reference and add the id element:

您可以通过引用来迭代数组并添加id元素:

foreach($arr as $key => &$val)
{
  $val['id'] = $key +1;
}

#1


1  

You can array_merge() the id to each subArray, e.g.

你可以通过array_merge()将id添加到每个subArray,例如

foreach ($arr as $key => $value) {
    $arr[$key] = array_merge(["id" => $key + 1], $value);
}

#2


0  

You can itterate the array by reference and add the id element:

您可以通过引用来迭代数组并添加id元素:

foreach($arr as $key => &$val)
{
  $val['id'] = $key +1;
}