note 31364 added to function.array-diff
| From: | ampf at egp dot up dot pt | Date: | Fri, 18 Apr 2003 14:34:11 +0000 |
| Subject: | note 31364 added to function.array-diff | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-46786@lists.php.net to get a copy of this message | ||
What I was needing was a way to diff multidimension arrays by a given key.... I came up with this.
/*
* Multidimension array subtract by a sub key.
*
* $array1 = array(
* array(
* "name" => "Foo",
* "mail" => "foo@moo.net"
* ),
* array(
* "name" => "Bar",
* "mail" => "bar@bie.com"
* )
* );
*
* $array2 = array(
* array(
* "name" => "Foo",
* "mail" => "foo@moo.net"
* ),
* array(
* "name" => "Xpto",
* "mail" => "xpto@xp.to"
* )
* );
*
* $result = array_subtract($array1, $array2, "name");
*
* $result = array(
* array(
* "name" => "Bar",
* "mail" => "bar@bie.com"
* )
* );
*
* Authors:
* Antonio Fernandes <ampf@egp.up.pt>
*
*/
function array_subtract($array1,$array2,$compareString) {
if (!is_array($array1) || !is_array($array2) || !$compareString) {
return false;
}
$arrResult = array();
foreach ($array1 as $arrInsideArray1) {
foreach ($array2 as $arrInsideArray2) {
$found=false;
if ($arrInsideArray1[$compareString]==$arrInsideArray2[$compareString]) {
$found=true;
break;
}
}
if (!$found) {
array_push($arrResult,$arrInsideArray1);
}
}
return $arrResult;
}
--
http://www.php.net/manual/en/function.array-diff.php
http://master.php.net/manage/user-notes.php?action=edit+31364
http://master.php.net/manage/user-notes.php?action=delete+31364
http://master.php.net/manage/user-notes.php?action=reject+31364