Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 345
PHPLover Avatar asked Apr 18 '13 15:04

PHPLover


People also ask

How do you add a key to an array?

To add a key/value pair to all objects in an array:Use the Array. forEach() method to iterate over the array. On each iteration, use dot notation to add a key/value pair to the current object. The key/value pair will get added to all objects in the array.

How do we store elements in a multidimensional array?

The total number of elements that can be stored in a multidimensional array can be calculated by multiplying the size of all the dimensions. For example: The array int x[10][20] can store total (10*20) = 200 elements. Similarly array int x[5][10][20] can store total (5*10*20) = 1000 elements.


2 Answers

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

That should do the trick.

like image 186
Stefan Candan Avatar answered Sep 21 '22 17:09

Stefan Candan


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);
like image 42
Manmohan Avatar answered Sep 25 '22 17:09

Manmohan