Laravel将新密钥推入数组

时间:2019-08-14 06:59:04

标签: php laravel

我有这样的数组数据

enter image description here

我想在条件为expected_count的情况下向数组添加新键if

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

所以结果将是这样

enter image description here

如何做到最好?

1 个答案:

答案 0 :(得分:2)

使用foreach遍历数组

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

我希望这会起作用。