note 91756 added to function.array-diff
| From: | firegun at terra dot com dot br | Date: | Wed, 24 Jun 2009 17:52:59 +0000 |
| Subject: | note 91756 added to function.array-diff | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-157434@lists.php.net to get a copy of this message | ||
Hello guys,
I´ve been looking for a array_diff that works with recursive arrays, I´ve tried the ottodenn
at gmail dot com function but to my case it doesn´t worked as expected, so I made my own. I´ve
haven´t tested this extensively, but I´ll explain my scenario, and this works great at that
case :D
We got 2 arrays like these:
$aArray1['marcie'] = array('banana' => 1, 'orange' => 1,
'pasta' => 1);
$aArray1['kenji'] = array('apple' => 1, 'pie' => 1,
'pasta' => 1);
$aArray2['marcie'] = array('banana' => 1, 'orange' => 1);
As array_diff, this function returns all the items that is in aArray1 and IS NOT at aArray2, so the
result we should expect is:
$aDiff['marcie'] = array('pasta' => 1);
$aDiff['kenji'] = array('apple' => 1, 'pie' => 1,
'pasta' => 1);
Ok, now some comments about this function:
- Different from the PHP array_diff, this function DON´T uses the === operator, but the ==, so 0
is equal to '0' or false, but this can be changed with no impacts.
- This function checks the keys of the arrays, array_diff only compares the values.
I realy hopes that this could help some1 as I´ve been helped a lot with some users experiences.
(Just please double check if it would work for your case, as I sad I just tested to a scenario like
the one I exposed)
function arrayRecursiveDiff($aArray1, $aArray2) {
$aReturn = array();
foreach ($aArray1 as $mKey => $mValue) {
if (array_key_exists($mKey, $aArray2)) {
if (is_array($mValue)) {
$aRecursiveDiff = $this->arrayRecursiveDiff($mValue, $aArray2[$mKey]);
if (count($aRecursiveDiff)) { $aReturn[$mKey] = $aRecursiveDiff; }
} else {
if ($mValue != $aArray2[$mKey]) {
$aReturn[$mKey] = $mValue;
}
}
} else {
$aReturn[$mKey] = $mValue;
}
}
return $aReturn;
}
----
Server IP: 64.71.164.2
Probable Submitter: 189.101.234.207
----
Manual Page -- http://www.php.net/manual/en/function.array-diff.php
Edit -- https://master.php.net/note/edit/91756
Del: integrated -- https://master.php.net/note/delete/91756/integrated
Del: useless -- https://master.php.net/note/delete/91756/useless
Del: bad code -- https://master.php.net/note/delete/91756/bad+code
Del: spam -- https://master.php.net/note/delete/91756/spam
Del: non-english -- https://master.php.net/note/delete/91756/non-english
Del: in docs -- https://master.php.net/note/delete/91756/in+docs
Del: other reasons-- https://master.php.net/note/delete/91756
Reject -- https://master.php.net/note/reject/91756
Search -- https://master.php.net/manage/user-notes.php