note 31364 deleted from function.array-diff by derick

From: Date: Fri, 02 Feb 2007 10:24:07 +0000
Subject: note 31364 deleted from function.array-diff by derick
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-122535@lists.php.net to get a copy of this message
Note Submitter: ampf at egp dot up dot pt ---- What I was needing was a way to diff multidimension arrays by a given key.... I came up with this. <?php /* * 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; } ?>

« previous php.notes (#122535) next »