php 如何在多维数组中插入新的键和值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16087572/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to insert a new key and value in multidimensional array?
提问by PHPLover
Following is the output of my multidimensional array $csmap_data
以下是我的多维数组的输出 $csmap_data
Array
(
[0] => Array
(
[cs_map_id] => 84
[cs_subject_id] => 1
)
[1] => Array
(
[cs_map_id] => 85
[cs_subject_id] => 5
)
[flag] => 1
)
Initially there was no [flag] => 1
key-value in the array, I added it to the array $csmap_data
.
But I want to add the [flag] => 1
in the above two array elements, not as a separate array element. In short I wanted following output :
最初[flag] => 1
数组中没有键值,我将其添加到数组中$csmap_data
。但是我想[flag] => 1
在上面的两个数组元素中添加 ,而不是作为一个单独的数组元素。简而言之,我想要以下输出:
Array
(
[0] => Array
(
[cs_map_id] => 84
[cs_subject_id] => 1
[flag] => 1
)
[1] => Array
(
[cs_map_id] => 85
[cs_subject_id] => 5
[flag] => 1
)
)
The code I was trying to achieve this is as follows, but couldn't get the desired output:
我试图实现的代码如下,但无法获得所需的输出:
if (!empty($csmap_data)) {
foreach($csmap_data as $csm) {
$chapter_csmap_details = $objClassSubjects->IsClassSubjectHasChapters($csm['cs_map_id']);
$csmap_data ['flag'] = 1;
}
}
Can anyone help me out in obtaining the desired output as I depicted? Thanks in advance.
任何人都可以帮助我获得我所描述的所需输出吗?提前致谢。
回答by Stefan Candan
<?
foreach($csmap_data as $key => $csm)
{
$csmap_data[$key]['flag'] = 1;
}
That should do the trick.
这应该够了吧。
回答by Manmohan
You can also do it using php array functions
您也可以使用 php 数组函数来完成
$csmap_data = array_map(function($arr){
return $arr + ['flag' => 1];
}, $csmap_data);
UPDATE:
to use multiple variables in callback function of array_map
function we can do it by use
更新:要在函数的回调函数中使用多个变量,array_map
我们可以通过use
$flagValue = 1;
$csmap_data = array_map(function($arr) use ($flagValue){
return $arr + ['flag' => $flagValue];
}, $csmap_data);