简体   繁体   English

使用PHP对多维数组进行排序

[英]Sort a multi-dimensional array using PHP

My array is created like this: 我的数组是这样创建的:

$c3_array[$c3_count]["box"] = $box;
$c3_array[$c3_count]["subseries"] = $subseries;
$c3_array[$c3_count]["foldertitle"] = $foldertitle;
$c3_array[$c3_count]["uri"] = $uri;

How can I sort the array based on "box" ASC, then based on "foldertitle" ASC? 如何基于“ box” ASC,然后基于“ foldertitle” ASC,对数组进行排序?

Thanks! 谢谢!

You could use usort and create your own comparison function. 您可以使用usort并创建自己的比较函数。 Here is a simple example, that might or might not work, depending on what the actual values in the arrays are, but it should at least give you the idea. 这是一个简单的示例,根据数组中的实际值是什么,可能会或可能不会起作用,但至少应能使您了解。

function mysort ($a, $b)
{
    if ($a['box'] > $b['box']) return 1;
    if ($a['box'] < $b['box']) return -1;
    if ($a['foldertitle'] > $b['foldertitle']) return 1;
    if ($a['foldertitle'] < $b['foldertitle']) return -1;
    return 0;
}

usort($c3_array, 'mysort');

I think array_multisort() is what you need. 我认为array_multisort()是您所需要的。 Check the PHP documentation 查看PHP文档

Using array_multisort , as in example 3. 使用array_multisort ,如示例3所示。

$boxes = array();
$foldertitles = array();
foreach($c3_array as $key => $array) {
    $boxes[$key] = $array['box'];
    $foldertitles[$key] = $array['foldertitle'];
}

array_multisort($boxes, SORT_ASC, $foldertitles, SORT_ASC, $c3_array);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM