在PHP

时间:2015-08-11 08:35:39

标签: php sorting

我有以下数组:

array(10) { 
        [0]=> array(109) {  
            ["id"]=> string(4) "2632", ["_category_sortorder"] => 8, ["_sortorder" => 1] 
        },
        [1]=> array(109) {  
            ["id"]=> string(4) "2635", ["_category_sortorder"] => 5, ["_sortorder" => 2] 
        },
        ...
}

我想根据两个标准对其进行排序:

a)按_category_sortorder asc (优先级)

b)_sortorder asc

我试过了:

foreach($resources as $k => $v) {
    $sort[$k]['_category_sortorder'] = $resources[$k]['_category_sortorder'];
    $sort[$k]['_sortorder'] = $resources[$k]['_sortorder'];
 }

array_multisort($sort['_category_sortorder'], SORT_ASC, $sort['_sortorder'], SORT_ASC, $resources);

但它没有按预期工作。有什么建议吗?

2 个答案:

答案 0 :(得分:1)

试试这个,

$sort = array(
                array("id"=>"263", "_category_sortorder"=> 8, "_sortorder" => 1),
                array( "id"=>  "145", "_category_sortorder" => 155, "_sortorder" => 2),
                array( "id"=>  "2145", "_category_sortorder" => 55, "_sortorder" => 12),
                array( "id"=>  "3145", "_category_sortorder" => 155, "_sortorder" => 10),
            );

usort($sort, function(array $a, array $b) {
    return $b['_category_sortorder'] - $a['_category_sortorder'];
});


echo '<pre>';
print_r($sort);
echo '</pre>';

答案 1 :(得分:0)

我认为有一个简单的解决方案,但这个代码块正在做的是工作: 您将数组拆分为子数组,仅包含具有相同_category_sortorder值的元素。然后用usort对每个子数组进行排序。最后,将它们合并在一起。

<?php
    $array = [
        ['id' => 1, '_category_sortorder' => 2, '_sortorder' => 1],
        ['id' => 2, '_category_sortorder' => 2, '_sortorder' => 3],
        ['id' => 3, '_category_sortorder' => 3, '_sortorder' => 19],
        ['id' => 4, '_category_sortorder' => 1, '_sortorder' => 2],
        ['id' => 5, '_category_sortorder' => 1, '_sortorder' => 1],
    ];

    foreach ($array as $value) {
        if (!isset($newElements[$value['_category_sortorder']]))
            $newElements[$value['_category_sortorder']] = [];
        $newElements[$value['_category_sortorder']][] = $value;
    }


    $array = [];
    foreach ($newElements as $key => $value) {
        usort($value, function($a, $b) {
            return strcmp($a["_sortorder"], $b["_sortorder"]);
        });
        $array[$key] = $value;
    }

    ksort($array);
    $new = [];
    foreach ($array as $value) {
        $new = array_merge($new, $value);
    }
    echo "<pre>".print_r($new, true).'</pre>';