Forum Moderators: coopster

Message Too Old, No Replies

array filter on two-dimensional array

         

Lupi

6:43 pm on Oct 24, 2010 (gmt 0)

10+ Year Member



Hi,

I have a two-dimensional array in PHP of the kind below that I would like to array_filter (or at least I believe that array_filter would be a the function of choice here, but I am a novice).


$data = array();
$data[0] = array("A","sometext",73);
$data[1] = array("A","sometext",72);
$data[2] = array("A","sometext",60);
$data[3] = array("B","sometext",100);
$data[4] = array("B","sometext",101);
$data[5] = array("C","sometext",120);
$data[6] = array("C","sometext",115);


This is the output I am aiming for:


Array (
[2] => Array ( [0] => A [1] => sometext [2] => 60 )
[3] => Array ( [0] => B [1] => sometext [2] => 100 )
[6] => Array ( [0] => C [1] => sometext [2] => 115 ) )


Basically, I want to grab the one entry of all the As, the one of all the Bs and the one of all the Cs with the lowest number.

I would appreciate if you have any ideas - is array_filter in fact the best solution here, and what would the callback function have to look like?

Thanks!

enigma1

9:46 am on Oct 25, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Why array_filter is better? you will need a function and code. Using some code maybe simpler.


$result_array = $tmp_array = array();
for($i=0, $j=count($data); $i<$j; $i++) {
$key = $data[$i][0];
$value = $data[$i][2];
if( isset($tmp_array[$key]) && $result_array[$tmp_array[$key]][2] <= $value) continue;
if( isset($tmp_array[$key]) ) unset($result_array[$tmp_array[$key]]);

$tmp_array[$key] = $i;
$result_array[$i] = $data[$i];
}