Home > Software engineering >  How can I add an element to my dimensional array
How can I add an element to my dimensional array

Time:12-05

I have a dimensional array, and I would like to add an element in my lessons array

this is my array

$array = [
    [
      'id' => 1,
      'lessons' => [
         [
           'name' => 'PHP',
         ],
         [
           'name' => 'Python',
         ]
     ]
   ],
   [
      'id' => 1,
      'lessons' => [
         [
           'name' => 'Java',
         ],
         [
           'name' => 'Ruby',
         ]
     ]
   ],
];

I would like to add flag element to my lessons,

Desired output:

$array = [
        'id' => 1,
        'lessons' => [
           [
             'name' => 'PHP',
             'flag' => true
           ],
           [
             'name' => 'Python',
             'flag' => true
           ]
       ]
    ];

I would like to do that without a nested foreach or a foreach. I tried with array_map

Code I tried :

$csmap_data = array_map(function($array){
    return $topics['lessons']   ['flag' => true];
}, $topics);

CodePudding user response:

Try this:

$array['lessons'] = array_map(function($lesson) {
    $lesson['flag'] = true;
    return $lesson;
}, $array['lessons']);

print_r($array);

CodePudding user response:

foreach( $array['lessons'] as $lesson )
{
   $lesson['flag'] = true;
}
  •  Tags:  
  • php
  • Related