Andi Siswanto
Andi Siswanto

Reputation: 59

Laravel push new key to array

I have array data like this

enter image description here

I want to add new key expected_count to the array with if conditional,

if flags key == is_join ? expected_count=2
if flags key == is_grade ? expected_count=1

So the result will be like this

enter image description here

How the best way to do this?

Upvotes: 0

Views: 193

Answers (1)

Sagar Gautam
Sagar Gautam

Reputation: 9369

Use foreach to iterate over the array

foreach($data['sections'] as $key => $section){
     if(array_key_exists('is_join', $section['flags'])){
         $data['sections'][$key]['flags']['is_join']['expected_count'] = 2;
     }
     if(array_key_exists('is_grade', $section['flags'])){
         $data['sections'][$key]['flags']['is_grade']['expected_count'] = 1;
     }
}

I hope this will work.

Upvotes: 2

Related Questions