如何在多维数组中插入新的键和值?

时间:2023-01-26 14:43:10

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.

有人能帮我得到我描述的所需输出吗?提前谢谢。

2 个解决方案

#1


20  

<?
 foreach($csmap_data as $key => $csm)
 {
  $csmap_data[$key]['flag'] = 1;
 }

That should do the trick.

这应该很管用。

#2


6  

You can also do it using php array functions

还可以使用php数组函数来实现

$csmap_data = array_map(function($arr){
    return $arr + ['flag' => 1];
}, $csmap_data);

#1


20  

<?
 foreach($csmap_data as $key => $csm)
 {
  $csmap_data[$key]['flag'] = 1;
 }

That should do the trick.

这应该很管用。

#2


6  

You can also do it using php array functions

还可以使用php数组函数来实现

$csmap_data = array_map(function($arr){
    return $arr + ['flag' => 1];
}, $csmap_data);