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

Below 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 key in the array [flag] => 1, I added it to the array $csmap_data. But I want to add [flag] => 1to the two aforementioned array elements, and not as a separate array element. In short, I need the 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 tried to achieve looks like this, but cannot get the desired result:

if (!empty($csmap_data)) {  
                    foreach($csmap_data as $csm) {
                        $chapter_csmap_details = $objClassSubjects->IsClassSubjectHasChapters($csm['cs_map_id']);

                            $csmap_data ['flag'] = 1;


                    }
            }

Can someone help me get the desired result as I pictured? Thanks in advance.

+7
source share
2 answers
<?
 foreach($csmap_data as $key => $csm)
 {
  $csmap_data[$key]['flag'] = 1;
 }

That should do the trick.

+26
source

You can also do this using php array functions

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

UPDATE: array_map, use

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

All Articles