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

南楼画角 提交于 2019-11-27 02:24:44

问题


Following is the output of my multidimensional array $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 :

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.


回答1:


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

That should do the trick.




回答2:


You can also do it using php array functions

$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

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


来源:https://stackoverflow.com/questions/16087572/how-to-insert-a-new-key-and-value-in-multidimensional-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!