note 108176 added to function.array-filter

From: Date: Wed, 04 Apr 2012 20:09:44 +0000
Subject: note 108176 added to function.array-filter
Groups: php.notes 
Request: Send a blank email to php-notes+get-186972@lists.php.net to get a copy of this message
<?php // ARRAY FILTER RECURSIVE USING CLASS, STATIC METHOD, AND ANONYMOUS CALLBACK FUNCTION // NOTE THAT THE CALLBACK HAS ACCESS TO BOTH THE KEY AND VALUE // THE CLASS (FOR YOU TO COPY) class ArrayUtil { public static function FilterRecursive(Array $source, $fn) { $result = array(); foreach ($source as $key => $value) { if (is_array($value)) { $result[$key] = self::FilterRecursive($value, $fn); continue; } if ($fn($key, $value)) { $result[$key] = $value; // KEEP continue; } } return $result; } } // EXAMPLE ANONYMOUS CALLBACK FUNCTION $fn = function ($key, $value) { if (strpos($key, 'drop') !== FALSE) { return FALSE; // DROP } return TRUE; // KEEP }; // EXAMPLE PRE FILTER TEST DATA $preFilter = array( 'a' => 'one', 'b' => array( 'example_drop' => 'filter me out', 'example_keep' => 'keep me', ), 'c' => 'three', ); // EXAMPLE USAGE CODE echo '// print_r($preFilter);' . "\n"; print_r($preFilter); $postFilter = ArrayUtil::FilterRecursive($preFilter, $fn); echo "\n"; echo '// print_r($postFilter);' . "\n"; print_r($postFilter); /* OUTPUT OPEN // print_r($preFilter); Array ( [a] => one [b] => Array ( [example_drop] => filter me out [example_keep] => keep me ) [c] => three ) // print_r($postFilter); Array ( [a] => one [b] => Array ( [example_keep] => keep me ) [c] => three ) OUTPUT CLOSE */ ---- Server IP: 69.147.83.197 Probable Submitter: 76.169.174.129 ---- Manual Page -- http://www.php.net/manual/en/function.array-filter.php Edit -- https://master.php.net/note/edit/108176 Del: integrated -- https://master.php.net/note/delete/108176/integrated Del: useless -- https://master.php.net/note/delete/108176/useless Del: bad code -- https://master.php.net/note/delete/108176/bad+code Del: spam -- https://master.php.net/note/delete/108176/spam Del: non-english -- https://master.php.net/note/delete/108176/non-english Del: in docs -- https://master.php.net/note/delete/108176/in+docs Del: other reasons-- https://master.php.net/note/delete/108176 Reject -- https://master.php.net/note/reject/108176 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#186972) next »