note 112903 added to function.array-diff
| From: | ross dot killen at gmail dot com | Date: | Mon, 05 Aug 2013 10:36:14 +0000 |
| Subject: | note 112903 added to function.array-diff | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-195870@lists.php.net to get a copy of this message | ||
I was looking for a function to find the difference between 2 arrays with respect to their values as
opposed to their structure. Let's say we have 2 arrays, identical in structure and I'm
looking to output a 3rd array, again, identical in structure but containing the difference in the
value of leaf nodes. This could be suitable for comparing 2 data blocks over different date ranges
for example.
function array_diff_values_percent($v1, $v2)
{
return (!empty($v2) && is_numeric($v1) && is_numeric($v2)) ?
round(($v1-$v2)/$v2*100,2).'%' : '-';
}
function array_diff_values($a1, $a2, $callback)
{
if(!is_array($a1) || !is_array($a2)) return array();
$diff = array();
foreach($a1 as $key=>$val)
{
$diff[$key] = is_array($val) ? array_diff_values($val, $a2[$key], $callback) :
call_user_func_array($callback, array($val, $a2[$key]));
}
return $diff;
}
// Example
$array1 = array('key1'=>array('val1'=>4,
'val2'=>5,
'val3'=>6));
$array2 = array('key1'=>array('val1'=>3,
'val2'=>4,
'val3'=>5));
print_r(array_diff_values($array1, $array2, 'array_diff_values_percent'));
/* Outputs
Array
(
[key1] => Array
(
[val1] => 33.33%
[val2] => 25%
[val3] => 20%
)
)
*/
----
Server IP: 69.147.83.199
Probable Submitter: 86.44.204.55
----
Manual Page -- http://php.net/manual/en/function.array-diff.php
Edit -- https://master.php.net/note/edit/112903
Del: integrated -- https://master.php.net/note/delete/112903/integrated
Del: useless -- https://master.php.net/note/delete/112903/useless
Del: bad code -- https://master.php.net/note/delete/112903/bad+code
Del: spam -- https://master.php.net/note/delete/112903/spam
Del: non-english -- https://master.php.net/note/delete/112903/non-english
Del: in docs -- https://master.php.net/note/delete/112903/in+docs
Del: other reasons-- https://master.php.net/note/delete/112903
Reject -- https://master.php.net/note/reject/112903
Search -- https://master.php.net/manage/user-notes.php