skip to Main Content

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);

2

Answers


  1. Try this:

    $array['lessons'] = array_map(function($lesson) {
        $lesson['flag'] = true;
        return $lesson;
    }, $array['lessons']);
    
    print_r($array);
    
    Login or Signup to reply.
  2. foreach( $array['lessons'] as $lesson )
    {
       $lesson['flag'] = true;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search