note 122505 deleted from function.array-walk-recursive by crell
| From: | crell@php.net | Date: | Tue, 12 Apr 2022 01:07:24 +0000 |
| Subject: | note 122505 deleted from function.array-walk-recursive by crell | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-218199@lists.php.net to get a copy of this message | ||
Note Submitter: seductiveapps.com
----
function walkArray (&$a, $keyCallback, $valueCallback, $k='', $level=0,
$path='') {
// usage : walkArray ($someRecursiveArray, 'walkArray_printKey',
'walkArray_printValue');
// can handle recursive arrays. a nested array is a recursive array.
// is faster, especially on large arrays, than RecuriveArrayIterator, see speed testing comment at
http://php.net/manual/en/class.recursiveiteratoriterator.php
// provides detailed information to callbacks on where in the data we are, something that
array_walk_recursive just doesnt do.
// passes data around as pointers, not copies of data.
if (
!function_exists($keyCallback)
&& !function_exists($valueCallback)
) {
return badResult (E_USER_ERROR, array (
'msg' => 'walkArray() was called without $keyCallback or
$valueCallback as existing function names. see also : call_user_func() in PHP manual.'
);
}
if (!is_array($a)) {
return badResult (E_USER_ERROR, array (
'msg' => 'walkArray() was called but $a parameter passed is not an
array.'
));
} else {
foreach ($a as $k=>&$v) {
$cd = array ( // callback data
'type' => 'key',
'path' => $path,
'level' => $level,
'k' => &$k,
'v' => &$v
);
if (!is_null($keyCallback)) call_user_func ($keyCallback, $cd);
if (is_array ($v)) {
walkArray ($a[$k], $keyCallback, $valueCallback, $k, $level+1,
$path.'/'.$k);
} else {
$cd['type'] = 'value';
if (!is_null($valueCallback)) call_user_func ($valueCallback, $cd);
}
}
}
return true;
}
function walkArray_printKey ($cd) {
echo '<div
style="background:blue;color:yellow;border-radius:5px;padding:2px;margin-top:5px;">'.PHP_EOL;
$indent = 20 * $cd['level'];
echo '<div style="padding-left:'.$indent.'px">'.PHP_EOL;
echo 'key : '.$cd['k'].'<br/>'.PHP_EOL;
echo 'path : '.$cd['path'].'<br/>'.PHP_EOL;
echo '</div>'.PHP_EOL;
echo '</div>'.PHP_EOL;
}
function walkArray_printValue ($cd) {
echo '<pre
style="background:green;color:white;border-radius:5px;padding:2px;margin-top:2px;">'.PHP_EOL;
$indent = 20 * $cd['level'];
echo '<div style="padding-left:'.$indent.'px">'.PHP_EOL;
echo 'key : '.$cd['k'].'<br/>'.PHP_EOL;
echo 'path : '.$cd['path'].'<br/>'.PHP_EOL;
echo 'value : '.$cd['v'].'<br/>'.PHP_EOL;
echo '</div>'.PHP_EOL;
echo '</pre>'.PHP_EOL;
}
// the only thing you have to change in this code is the badResult() function, but you could raise
an exception or return false