2016-11-04 62 views
0

有它內置如下所示(有一些我離開離開這個例子更多的值)的數組:使用的foreach多維數組收集值循環

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

但結果不同於我的預期。有什麼建議麼?

回答

2

有在你的代碼的兩大問題。首先,你與$filterSortSaveArray['cars']引用未定義的值,因爲在原始數組的第一級無'cars'關鍵。其次,通過在循環分配值$field_values['car_filter_sort_id']$field_values['car_id']你只是重寫他們在每個迭代。您需要使用[]=運算符(這相當於應用)將值推入數組。

試試這個:

$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'] 
    ]; 
    } 
} 
+0

大,這個工作了。非常感謝你的解釋:) –