Wenuka
Wenuka

Reputation: 1082

how to extract specific amount of data from a associative array with a maximum value for a certain key

Lets assume,

$array1 = array(
array('id'=>'a','age'=>21),
array('id'=>'b','age'=>23),
array('id'=>'c','age'=>56),
array('id'=>'d','age'=>13),
array('id'=>'a','age'=>24)
);

Here I want to extract the entries with maximum age (assume three entries) and store in a new array, say $max_array. So,

$max_array = array(
array('id'=>'c','age'=>56),
array('id'=>'a','age'=>24),
array('id'=>'b','age'=>23)
);

Here the way I did is, as find out from the StackOverflow itself, first find the entry with maximum value using array_keys($array1 ,max($array1 )) and then store it in $max_array, pop it from the $array1 and then redo the process for 3 times.

But since in $array1, the first key is id, it take the maximum of id, not the age. If not following code works fine, please let me know if I can make it more efficient.

$max_ppl=array();
for ($i=0; $i <3 ; $i++) { 
    $max_ppl[] = max($array1);
    $ppl_time_sort = (array_keys($array1,max($array1)));
    unset($array1[$ppl_time_sort[0]]);
}
print_r($max_ppl);

Upvotes: 0

Views: 62

Answers (3)

Crunch Much
Crunch Much

Reputation: 1527

Column age in an array using array_column() and then sort it using array_multisort().

<?php

$arr1 = array_column($array1, 'age');
array_multisort($arr1, SORT_DESC, $array1);

var_dump($array1);

Upvotes: 1

Dev. Joel
Dev. Joel

Reputation: 1137

using array_multisort and array_slice for the first three values if you want to get the three minor change

array_multisort($Ages, SORT_DESC, $array); // SORT_DESC for SORT_ASC

code complete

echo "<pre>";
 $Ages= array();
  foreach ($array as $key => $row)
   {
      $Ages[$key] = $row['age'];
  }
  array_multisort($Ages, SORT_DESC, $array);

  print_r(array_slice($array,0, 3));
echo "</pre>";

Upvotes: 1

Dave
Dave

Reputation: 111

you can try like this, It's very simple and convenient;

$array1 = array(
            array('id'=>'a','age'=>21),
            array('id'=>'b','age'=>23),
            array('id'=>'c','age'=>56),
            array('id'=>'d','age'=>13),
            array('id'=>'a','age'=>24)
    );

    $ages = array_map(function($v){
        return $v['age'];
    }, $array1);

    array_multisort($ages, SORT_DESC, $array1 );

    var_dump($array1, array_slice($array1, 0, 3));

Upvotes: 1

Related Questions