php - how to sort multiarray with the sub value -
i have multidimensional array unexpected numbers of product groups
i want sort these groups lowest count number these groups
as example : first group after resort input product group because has lowest count number , input product group ..etc
how this?
<?php $a = // output product group array( array('id' => 117, 'name' => 'monitor', 'count' => 60), array('id' => 118, 'name' => 'printer', 'count' => 16), array('id' => 119, 'name' => 'sound card', 'count' => 19), // input product group array( array('id' => 120, 'name' => 'keyboard', 'count' => 11), array('id' => 121, 'name' => 'hard', 'count' => 21), array('id' => 122, 'name' => 'mouse', 'count' => 24) ) ) ; // code does't works // obtain list of columns foreach ($a $key => $row) { $count[$key] = $row['count']; } // sort data mid descending // add $data last parameter, sort common key array_multisort($count, sort_asc, $a); echo $count[$key]; ?>
i'm confused structure of $a. products 120-122 inside array sibling products 117-119. surely there should array wrapping "group" of 117-119? i'm going assume that's intended, otherwise makes no sense. should be:
$a = array( array( array('id' => 117, 'name' => 'monitor', 'count' => 60), array('id' => 118, 'name' => 'printer', 'count' => 16), array('id' => 119, 'name' => 'sound card', 'count' => 19), ), array( array('id' => 120, 'name' => 'keyboard', 'count' => 11), array('id' => 121, 'name' => 'hard', 'count' => 21), array('id' => 122, 'name' => 'mouse', 'count' => 24), ), );
now if understand correctly, want sort groups according lowest count of product inside group. can custom sort function so:
// first calculate lowest count each group foreach ($a $key => $group) { $lowestcount = null; foreach ($group $product) { if ($lowestcount === null || $lowestcount > $product['count']) { $lowestcount = $product['count']; } } $a[$key]['lowestcount'] = $lowestcount; } // sort groups according lowest count usort($a, function($group1, $group2) { return $group1['lowestcount'] - $group2['lowestcount']; }); // clean 'lowestcount' variables foreach ($a $key => $group) unset($a[$key]['lowestcount']);
the output contain group of 120-122 first, group of 117-119, because 11 less 16. if that's not wanted, please clarify!
edit: old php (5.2 , below), change sort code to:
// sort groups according lowest count if (!function_exists('groupsort')) { function groupsort($group1, $group2) { return $group1['lowestcount'] - $group2['lowestcount']; } } usort($a, 'groupsort');
Comments
Post a Comment