In Laravel 10 / PHP 8.2 app I try to collect data into one array using collapse
in set requests where some params are changed:
$data = []
FOR(...
$data = Arr::collapse($data, $query->where('some_field', $someParameter)->get()->toArray())
ENDFOR,
but that does not work and resulting array is empty. Do I need to use some other method, then collapse
?
Arr::collapse()
accepts only one argument and it must be an array of arrays.
In your loop, you're passing multiple arguments:
$data = Arr::collapse($data, $query->where(...)->get()->toArray());
Only the first argument is used and the second is ignored.
Internally it works like this:
public static function collapse($array)
{
$results = [];
foreach ($array as $values) {
if ($values instanceof Collection) {
$values = $values->all();
} elseif (! is_array($values)) {
continue;
}
$results[] = $values;
}
return array_merge([], ...$results);
}
I don't know exactly how your loop works but you can try to do the following:
$data = [];
for (...) {
$data[] = $query->where('some_field', $someParameter)->get()->toArray();
}
$data = Arr::collapse($data);