如何在PHP中显示已排序的子数组的键?

时间:2011-01-17 03:20:21

标签: php arrays sorting multidimensional-array

我对数组比较新,所以请耐心等待。情况: a = 1 b = 3 c = 5

第一个问题:如何回显最大值的键:“c”到页面?
第二个问题:在array_multisort中($ count,SORT_DESC,$ elecCondSort);下面,如果我从参数中删除$ elecCondSort,为什么它不起作用?

不确定我的代码是否是最好的方法(如果存在更简单的解决方案,请购买)。请解释任何修改。

$elecCondSort = array(
    array ("Condition" => "New", "Count" => 5),
    array ("Condition" => "Used", "Count" => 3),
    array ("Condition" => "Manufacturer refurbished", "Count" => 1),
);

foreach ($elecCondSort as $key => $row)
{
    $condition[$key] = $row["Condition"]; 
    $count[$key] = $row["Count"]; 
}

array_multisort($count, SORT_DESC, $elecCondSort);

echo $condition[$key].'<br>';

1 个答案:

答案 0 :(得分:0)

如果您想要最大计数值和条件标签,您可以:

$elecCondSort = array(
    array ("Condition" => "New", "Count" => 5),
    array ("Condition" => "Used", "Count" => 3),
    array ("Condition" => "Manufacturer refurbished", "Count" => 1),
);

$maxValue = 0;
$labelMaxValue = '';
foreach ($elecCondSort as $item) {
   $labelMaxValue = ($item['Count']>$maxValue) ? $item['Condition'] : $labelMaxValue;
   $maxValue = ($item['Count']>$maxValue) ? $item['Count'] : $maxValue;
}

echo $labelMaxValue;
echo $maxValue;

我真的不明白你想如何对数组进行排序,但是这段代码应该是最大值。