I have this two arrays:
$arr1=array( array("id" => 8, "name" => "test1"),
array("id" => 4, "name" => "test2"),
array("id" => 3, "name" => "test3")
);
$arr2=array( array("id" => 3),
array("id" => 4)
);
How can i "extract" arrays from $arr1, where id have same value in $arr2, into a new array and leave the extracted array also in a new array, without taking into account key orders?
The output i am looking for should be:
$arr3=array(
array("id" => 8, "name" => "test1")
);
$arr4=array( array("id" => 4, "name" => "test2"),
array("id" => 3, "name" => "test3")
);
Thanks
The array_diff_assoc() function compares the keys and values of two (or more) arrays, and returns the differences. This function compares the keys and values of two (or more) arrays, and return an array that contains the entries from array1 that are not present in array2 or array3, etc.
The array_intersect() function compares the values of two (or more) arrays, and returns the matches. This function compares the values of two or more arrays, and return an array that contains the entries from array1 that are present in array2, array3, etc.
The array_merge() is a builtin function in PHP and is used to merge two or more arrays into a single array. This function is used to merge the elements or values of two or more arrays together into a single array.
The array_diff() function compares the values of two (or more) arrays, and returns the differences.
I'm sure there's some ready made magical array functions that can handle this, but here's a basic example:
$ids = array();
foreach($arr2 as $arr) {
$ids[] = $arr['id'];
}
$arr3 = $arr4 = array();
foreach($arr1 as $arr) {
if(in_array($arr['id'], $ids)) {
$arr4[] = $arr;
} else {
$arr3[] = $arr;
}
}
The output will be the same as the one you desired. Live example:
http://codepad.org/c4hOdnIa
You can use array_udiff()
and array_uintersect()
with a custom comparison function.
function cmp($a, $b) {
return $a['id'] - $b['id'];
}
$arr3 = array_udiff($arr1, $arr2, 'cmp');
$arr4 = array_uintersect($arr1, $arr2, 'cmp');
I guess this may end up being slower than the other answer, as this will be going over the arrays twice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With