Marcel Wasilewski Marcel Wasilewski - 1 month ago 11
PHP Question

Collecting values from a multidimensional array using foreach loops

There is an array which is built looks like the following (with some more values which i left away for this example):

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


I want to build another array from the above in the following form:

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


I tried to achieve this with following function:

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


But the the result differs from what I have expected. Any suggestions?

Answer

There are two big issues in your code. First, are you referencing undefined value with $filterSortSaveArray['cars'], since there is no 'cars' key in the first level of the original array. Second, by assigning values to $field_values['car_filter_sort_id'] and $field_values['car_id'] in the loop you are just overriding them in each iteration. You need to push the values into an array using []= operator (which is equivalent to applying array_push()).

Try this:

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