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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:30:04  来源:igfitidea点击:

How to insert a new key and value in multidimensional array?

phparraysmultidimensional-arrayassociative-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] => 1key-value in the array, I added it to the array $csmap_data. But I want to add the [flag] => 1in 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_mapfunction 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);