note 38597 deleted from function.array-filter by cmb

From: Date: Sun, 06 Oct 2019 08:11:25 +0000
Subject: note 38597 deleted from function.array-filter by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-212495@lists.php.net to get a copy of this message
Note Submitter: Jeremy ---- 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** ) )

« previous php.notes (#212495) next »