我有多维数组,产品组数量超预期
我想按所有这些组的最低计数编号对所有这些组进行排序
作为示例 :度假后的第一个组将是输入产品组,因为它具有最低计数数,然后是输入产品组..etc
怎么做?
<?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];
?>
答案 0 :(得分: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');