note 38597 added to function.array-filter

From: Date: Mon, 29 Dec 2003 18:31:35 +0000
Subject: note 38597 added to function.array-filter
Groups: php.notes 
Request: Send a blank email to php-notes+get-62644@lists.php.net to get a copy of this message
Here is a nice little function which will apply a callback function recursively over a multidimensional array. If the callback function returns false, then it replaces the value of the array with $filtered_ouput. This function gracefully handles objects inside of arrays (and objects within objects within arrays, etc). It is specifically designed for your callback function to process on the array key's (unlike normal array_filter which filters on the values), but it could work on the array values depending on your test criteria (YMMV). <?PHP function array_key_filter_multi($array, $callback, $filtered_output = "") { $ret = array(); foreach($array as $key=>$value) { if($callback($key,$value)) { if(is_array($value)) { $ret[$key] = array_key_filter_multi($value, $callback, $filtered_output); } elseif(is_object($value)) { $ret[$key] = array_key_filter_multi(get_object_vars($value), $callback, $filtered_output); } else { $ret[$key]=$value; } } else { $ret[$key]=$filtered_output; } } return $ret; } ?> We use this to filter redundant data from debugging output. An example usage is: <? $callback_func = create_function('$key, $value', 'return ($key == "db" || $key == "smarty") ? false : true;'); echo "<PRE>" . print_r(array_key_filter_multi($_SESSION, $callback_func, "**filtered by function**"), true) . "</PRE>"; ?> Which filters all keys with "db" or "smarty" as their name (including objects which have a reference to those variables). The output of the above in a test case I did is the following: Array ( [userdata] => Array ( [sid] => a130e675d380e0e9fe47897922d719ac [not_in_db] => [user_id] => 1 [session_id] => 154 [permissions] => 1 [username] => tester ) [systemobjects] => Array ( [db] => **filtered by function** [smarty] => **filtered by function** ) ) ---- Manual Page -- http://www.php.net/manual/en/function.array-filter.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+38597 Delete -- http://master.php.net/manage/user-notes.php?action=delete+38597&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+38597&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#62644) next »