note 93965 modified in function.array-filter by danbrown

From: Date: Thu, 08 Oct 2009 20:04:56 +0000
Subject: note 93965 modified in function.array-filter by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-161570@lists.php.net to get a copy of this message
Here's a function that will filter a multi-demensional array. This filter will return only those items that match the $value given <?php /* * filtering an array */ function filter_by_value ($array, $index, $value){ if(is_array($array) && count($array)>0) { foreach(array_keys($array) as $key){ $temp[$key] = $array[$key][$index]; if ($temp[$key] == $value){ $newarray[$key] = $array[$key]; } } } return $newarray; } ?> Example: <?php $results = array( 0 => array('key1' => '1', 'key2' => 2, 'key3' => 3), 1 => array('key1' => '12', 'key2' => 22, 'key3' => 32) ); $nResults = filter_by_value($results, 'key2', '2'); ?> Output : array( 0 => array('key1' => '1', 'key2' => 2, 'key3' => 3) ); --was-- Here's a function that will filter a multi-demensional array. This filter will return only those items that match the $value given /* * filtering an array */ function filter_by_value ($array, $index, $value){ if(is_array($array) && count($array)>0) { foreach(array_keys($array) as $key){ $temp[$key] = $array[$key][$index]; if ($temp[$key] == $value){ $newarray[$key] = $array[$key]; } } } return $newarray; } Example: $results = array( 0 => array('key1' => '1', 'key2' => 2, 'key3' => 3), 1 => array('key1' => '12', 'key2' => 22, 'key3' => 32) ); $nResults = filter_by_value($results, 'key2', '2'); Output : array( 0 => array('key1' => '1', 'key2' => 2, 'key3' => 3) ); http://php.net/manual/en/function.array-filter.php

« previous php.notes (#161570) next »