使用foreach循环从多维数组中收集值

时间:2016-11-04 17:34:58

标签: php arrays

有一个构建的数组如下所示(在本例中我还剩下一些值):

    Array
    (
        [0] => Array
            (
                [id] => 44
                [cars] => Array
                    (
                        [0] => Array
                            (
                                [id] => 38
                            )

                        [1] Array
                            (
                                [id] => 39
                            )
                    )

            )

        [1] => Array
            (
                [id] => 45
                [cars] => Array
                    (
                        [0] => Array
                            (
                                [id] =>136
                            )

                        [1] =>Array
                            (
                                [id] =>137
                            )

                        [2] =>Array
                            (
                                [id] =>138
                            )
                    )
            )
)

我想通过以下形式从上面构建另一个数组:

Array

    (
       [0] =>  Array 
           (
               ['car_filter_sort_id'] => 44
               ['car_id'] => 38
           )
       [1] =>  Array 
           (
               ['car_filter_sort_id'] => 44
               ['car_id'] => 39
           )
       [2] =>  Array 
           (
               ['car_filter_sort_id'] => 45
               ['car_id'] => 136
           )
       [3] =>  Array 
           (
               ['car_filter_sort_id'] => 45
               ['car_id'] => 137
           )
       [4] =>  Array 
           (
               ['car_filter_sort_id'] => 45
               ['car_id'] => 138
           )
    )

我尝试使用以下功能实现此目的:

foreach($filterSortSaveArray as $filterSortSaveArray['cars'] => $value){
  $id =  $filterSortSaveArray['id'];
  foreach($value['cars'] as $value => $car){
    $field_values['car_filter_sort_id'] = $id;
    $field_values['car_id'] =  $car['id'];
  }
}

但结果与我的预期不同。有什么建议吗?

1 个答案:

答案 0 :(得分:2)

您的代码中存在两个大问题。首先,您是否使用$filterSortSaveArray['cars']引用未定义的值,因为原始数组的第一级中没有'cars'键。其次,通过在循环中为$field_values['car_filter_sort_id']$field_values['car_id']赋值,您只需在每次迭代中覆盖它们。您需要使用[]=运算符将值推送到数组中(相当于应用array_push())。

试试这个:

$result = [];

foreach($filterSortSaveArray as $k => $v) {
  if (!is_array($v['cars']))
    continue;

  $id = $v['id'];

  foreach ($v['cars'] as $i => $car){
    $result[] = [
      'car_filter_sort_id' => $id,
      'car_id' =>  $car['id']
    ];
  }
}