开发者

Sort a multi-dimensional array using PHP

My array is created like this:

$c3_array[$c3_count]["box"] = $box;
$c3_array[$c3_count]["sub开发者_高级运维series"] = $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?

Thanks!


You could use usort and create your own comparison function. 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. Check the PHP documentation


Using array_multisort, as in example 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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜