I have a Laravel query returning a list. I need to filter this list and pick a random item after filtering.
$places = getPlaces();
if ( count($places) > 0) {
$places = array_filter($places, "filter"); // 2016/08/25: see http://php.net/manual/en/function.array-filter.php
$randomPlace = $places[rand(0, count($places) - 1)];
}
This give an error:
array_filter() expects parameter 1 to be array, object give
If I cast $places to array the error goes but I get nothing:
$places = getPlaces();
if ( count($places) > 0) {
$places = (array)$places;
$places = array_filter($places, "filter");
$randomPlace = $places[rand(0, count($places) - 1)];
}
When I check count($places) I see there's only one item. The resultset has several.
To get around the filter issue I use Eloquent's toArray():
if ( count($places) > 0) {
$places = $places->toArray();
$places = array_filter($places, "filter");
if ( count($places) > 0) {
$randomPlace = $places[rand(0, count($places) - 1)];
}
}
This works for filter but I land into a couple of challenges:
I can't access $randomPlace as an object e.g. $randomPlace->name. I have to use array access, $randomPlace['name']. Since there are other methods expecting an object this means having to change/convert all these methods.
$places[rand(0, count($places) - 1)] gives an error, e.g.:
Undefined offset: 4
Other than having to change all methods to use arrays instead of objects (thereby loosing out on functionality), at the moment the only other method off my head is to create a function that iterates over $places and and puts the objects into an array.
Is there a better way of handling this?
Thanks.
$places->filter('filter')or try getting the values only, usingarray_values($places). My guess is thatarray_filterpreserves the keys and removed the item where key=4.