Php排序多维数组?
如何对以下数组进行排序 我有一个多维数组,其中包含每个品牌的总小时数Php排序多维数组?,php,arrays,sorting,multidimensional-array,Php,Arrays,Sorting,Multidimensional Array,如何对以下数组进行排序 我有一个多维数组,其中包含每个品牌的总小时数 $totalHours = array( 'brand' => array(), 'project' => array(), 'hours' => array() ); 输出如下(项目未填充): 现在我想根据“小时”字段对数组进行排序 我尝试过数组\u multisort,但似乎我
$totalHours = array(
'brand' => array(),
'project' => array(),
'hours' => array()
);
输出如下(项目未填充):
现在我想根据“小时”字段对数组进行排序
我尝试过数组\u multisort,但似乎我根本不知道这个函数是如何工作的,以及如何将它应用到这个数组中。
我已经能够用一行值对单个数组进行排序。如果我将其应用于这个问题,我将只对小时字段进行排序,而对其他字段不进行排序,因此数组已损坏
“project”实际上包含一个字符串。总是这样。在这个例子中,我没有填充它。你不能用一个数组*函数来填充它 如果(项目未填写)始终且品牌和小时的指数相等,则您可以执行以下操作:
$forsort = array_combine($totalHours["brands"],$totalHours["hours"]);
asort($forsort,SORT_NUMERIC);
$totalHours["brands"]=array_keys($forsort);
$totalHours["hours"]=array_values($forsort);
但是,这只是对您的问题的回答,根本不是最佳实践。array\u multisort应该可以工作:
$totalHours = array(
'brand' => array('Nike', 'Coke Cola', 'Converse'),
'project' => array(),
'hours' => array(28, 106, '2')
);
array_multisort($totalHours['hours'], $totalHours['brand']);
var_dump($totalHours);
这种数据格式不是很方便,因为品牌和时间之间没有直接关联,它们甚至位于不同的阵列中!另外,最后一个小时是字符串,而不是整数 我们必须创建一个中间数组来关联它们并对它们进行排序。然后我们将重新注入原始数组中的所有内容
// Make sure both arrays of brands and hours and the same size
if (count($totalHours['brand']) != count($totalHours['hours'])) {
throw new Exception('Invalid data!');
}
// Make sure every hour record is an integer, not a string
$totalHours['hours'] = array_map('intval', $totalHours['hours']);
// array_combine will sort all arrays based on the sorting of the first one
array_multisort($totalHours['hours'], $totalHours['brand'], $totalHours['project']);
编辑:使用
array\u multisort
最初是@delprks的想法。在这里,我将其应用于品牌和项目阵列。非常感谢。你能帮助我如何应用这个,包括“项目”数组吗?或者我必须首先分配数组中的值。我的解决方案不是最好的,因为我没有使用array\u multisort
。现在我读了其他答案,我认为@delprks’s可能更适合这种情况。我会想办法的。我已经编辑了我的答案,在品牌和项目阵列上使用了array\u multisort
。太棒了!非常感谢。我可以再加上$totalHours[“projects”]=array_值($forsort);是否要添加项目字段?
// Make sure both arrays of brands and hours and the same size
if (count($totalHours['brand']) != count($totalHours['hours'])) {
throw new Exception('Invalid data!');
}
// Make sure every hour record is an integer, not a string
$totalHours['hours'] = array_map('intval', $totalHours['hours']);
// array_combine will sort all arrays based on the sorting of the first one
array_multisort($totalHours['hours'], $totalHours['brand'], $totalHours['project']);