Array_udiff对象数组使得数组包含的对象只存在一个特定方法的实例
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'
Ok, so for clarity, I'll do it in one loop.
$matches = array();
$remainder = array();
// $index if you need to maintain index=>object relation
foreach($array as $index => $object) {
if($object->bar == "b")
$matches[] = $object;
else
$remainder[] = $object;
}
-- for loop
for($index=0,$count=count($array);$index<$count;$index++) {
if($object->bar == "b")
$matches[] = $array[$index];
else
$remainder[] = $array[$index];
}
--
then you would like to merge the result with the first index in $matches
$result = array_merge(array($matches[0]),$remainder);
If this is the case, then you just need to change the compare object body, which should do the trick in filtering the remaining objects out
return $obj_a->id == $obj_b->id ? 0 : 1;