I need to transorm an array of objects so that for instance, the array will only contain 1 object where the object property 'bar' = b.
So I'd like to turn:
Array ( [0] => stdClass Object (
[id] = 1
[foo] => 'a'
[bar] => 'b' )
[1] => stdClass Object (
[id] => 2
[foo] => 'a'
[bar] => 'c' )
[2] => stdClass Object (
[id] => 3
[foo] => 'y'
[bar] => 'b' ) )
into:
Array ( [0] => stdClass Object (
[id] = 1
[foo] => 'a'
[bar] => 'b' )
[1] => stdClass Object (
[id] => 2
[foo] => 'a'
[bar] => 'c' )
However, I need this to work on a larger scale, so I am stumped on how to combine array_filter, array_udiff and array_slice to get what I want. I was thinking that array_filter would get me all the keys where 'foo' = 'b'
. Then I could take this array and array_udiff it against the original to get the items where 'foo'=! 'b'
. Then I could slice the matches from the array_filter to get a single-key array... and merge that back with the array_udiff difference.
$matches = array_filter($array, "bar_filter");
$remainder = array_udiff($array, $matches, 'compare_objects');
$single = array_slice( $matches, 0, 1);
$result = array_merge($single, $remainder);
function foobar_filter($obj) {
if ( $obj->bar == 'b' ) {
return true;
} else {
return false;
}
}
function compare_objects($obj_a, $obj_b) {
return $obj_a->id = $obj_b->id;
}
My compare_objects function is off for sure, but I don't know what to put there. Would it be better to just run a second array_filter to get the non-matching items? I need to split the array into keys where 'bar'='b'
and where 'bar'!='b'
and merge it back together with only 1 object where 'bar'='b'