0

我有带有意外数量的产品组的多维数组

我想按所有这些组的最低计数对所有这些组进行排序

例如:度假村后的第一组将是输入产品组,因为它的计数最少,然后是输入产品组..等等

这个怎么做?

<?php
$a = 
// the 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),
// the 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)
      )
    )

;       
// this code does't works good
// Obtain a list of columns
foreach ($a as $key => $row) {
    $count[$key]  = $row['count'];
}
// Sort the data with mid descending
// Add $data as the last parameter, to sort by the common key
 array_multisort($count, SORT_ASC, $a);

 echo $count[$key];
?>
4

1 回答 1

0

我对 $a 的结构感到困惑。产品 120-122 位于与产品 117-119 同级的数组中。当然应该有另一个数组包装 117-119 的“组”?我将假设这是预期的,否则没有任何意义。所以应该是:

$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),
    ),
);

现在,如果我理解正确,您想根据组内任何产品的最低计数对组进行排序。您可以使用自定义排序功能来做到这一点,如下所示:

// first calculate the lowest count for each group
foreach ($a as $key => $group) {
    $lowestCount = null;
    foreach ($group as $product) {
        if ($lowestCount === null || $lowestCount > $product['count']) {
            $lowestCount = $product['count'];
        }
    }
    $a[$key]['lowestCount'] = $lowestCount;
}

// sort groups according to their lowest count
usort($a, function($group1, $group2) {
    return $group1['lowestCount'] - $group2['lowestCount'];
});

// clean up the 'lowestCount' variables
foreach ($a as $key => $group) unset($a[$key]['lowestCount']);

输出将首先包含 120-122 组,然后是 117-119 组,因为 11 小于 16。如果这不是您想要的,请澄清!

编辑:对于旧 PHP(5.2 及以下),将排序代码更改为:

// sort groups according to their lowest count
if (!function_exists('groupSort')) {
    function groupSort($group1, $group2) {
        return $group1['lowestCount'] - $group2['lowestCount'];
    }
}
usort($a, 'groupSort');
于 2013-09-24T16:53:11.017 回答