I’m consuming a web service that returns an array of objects called $viewData like so:
Array
(
[0] => stdClass Object
(
[id] => 64757
[title] => Frogger
[votes] => 1
[status] => gotit
)
[1] => stdClass Object
(
[id] => 64758
[title] => The Legend of Zelda
[votes] => 1
[status] => wantit
)
[2] => stdClass Object
(
[id] => 64759
[title] => Grand Theft Auto
[votes] => 1
[status] => wantit
)
)
I need to split this into two separate arrays – one that contains all the objects whose status is wantit, and the other whose status is gotit.
I can get one array out of it by using array_filter() with a custom function:
if(is_array($viewData) and (!empty($viewData))) {
function splitGames($v){
if ($v->status==="gotit") {
return true;
}
return false;
}
$gotEm = array_filter($viewData, "splitGames");
print_r($gotEm);
}
This function returns what I’d expect:
Array
(
[0] => stdClass Object
(
[id] => 64757
[title] => Frogger
[votes] => 1
[status] => gotit
)
)
Is there a way to automatically get what’s left of the original array into a second array, or do I need to have a second custom function that looks for a status of “wantit” and rerun array_filter() again on the original array?
If you need two arrays, you will need to call
array_filtertwice.Alternatively, you could start with two empty arrays and just loop once over
$viewData, placing each array member into one of the two arrays based upon thestatusvalue.Does that help?