note 71060 added to function.array-walk-recursive
| From: | adamdottpubattadamswickdottcom at osu1 dot php dot net | Date: | Fri, 10 Nov 2006 02:08:07 +0000 |
| Subject: | note 71060 added to function.array-walk-recursive | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-119576@lists.php.net to get a copy of this message | ||
Thanks to all of you in the prior posts.
I don't like the fact that the current version of array_walk_recursive() doesn't track all
array keys. This version will do that, as well as tracking array depth on multi-dimensional arrays.
- - - - - - -
Class Array_walk_recursive3 {
private $depth = -1;
private $userdata, $funcname;
public $status;
public $input;
public function __construct($input, $funcname, $userdata = "") {
$this->input = $input;
$this->funcname = $funcname;
$this->userdata = $userdata;
$this->status = $this->array_walk_recursive($this->input);
}
private function test_print(&$value, &$key)
{
echo str_repeat(" ", $this->depth)."$key holds ";
if (!is_array($value)) {
echo $value;
if (trim($value) == "banana") {
$value = "cherry";
$key = "c";
}
}
echo "\n";
}
private function array_walk_recursive(&$input) {
$funcname = array(&$this, $this->funcname);
if (!is_callable($funcname)) {
return false;
}
if (!is_array($input)) {
return false;
}
$this->depth++;
foreach (array_keys($input) AS $keyIdx => $key) {
$saved_value = $input[$key];
$saved_key = $key;
call_user_func_array($funcname, array(&$input[$saved_key], &$key));
if ($input[$saved_key] !== $saved_value || $saved_key !== $key) {
$saved_value = $input[$saved_key];
unset($input[$saved_key]);
$input[$key] = $saved_value;
}
if (is_array($input[$key])) {
if (!$this->array_walk_recursive($input[$key], $funcname)) return false;
$this->depth--;
}
}
return true;
}
}
$sweet = array('a' => 'apple', 'b' => 'banana');
$fruits = array('sweet' => $sweet, 'sour' => 'lemon');
$fruitObj = new Array_walk_recursive3($fruits, 'test_print');
echo $fruitObj->status;
$newFruitArr = $fruitObj->input;
print_r($fruits);
print_r($newFruitArr);
----
Server IP: 216.194.113.175
Probable Submitter: 66.170.212.125
----
Manual Page -- http://www.php.net/manual/en/function.array-walk-recursive.php
Edit -- https://master.php.net/note/edit/71060
Del: integrated -- https://master.php.net/note/delete/71060/integrated
Del: useless -- https://master.php.net/note/delete/71060/useless
Del: bad code -- https://master.php.net/note/delete/71060/bad+code
Del: spam -- https://master.php.net/note/delete/71060/spam
Del: non-english -- https://master.php.net/note/delete/71060/non-english
Del: in docs -- https://master.php.net/note/delete/71060/in+docs
Del: other reasons-- https://master.php.net/note/delete/71060
Reject -- https://master.php.net/note/reject/71060
Search -- https://master.php.net/manage/user-notes.php