PHP数组复杂排序

时间:2017-06-15 02:12:17

标签: php arrays sorting

我有一个已生成的复杂数组,我正在尝试按['file_date']对其进行排序。降序。这是:

Array ( 
    ['images'] => Array ( 
        ['93-1138446.jpg'] => Array ( 
            ['file_title'] => '93-1138446', 
            ['file_path'] => 'gallery-images-1435/93-1138446.jpg', 
            ['thumb_path'] => 'resources/cache/275x275-75-d3cc92863d4f10bb6cf733159689a0e660fe5847df52beb531fa45b584876f0b.jpg', 
            ['file_date'] => '1497471649'
        ),
        ['93-8315415.jpg'] => Array ( 
            ['file_title'] => '93-8315415', 
            ['file_path'] => 'gallery-images-1435/93-8315415.jpg', 
            ['thumb_path'] => 'resources/cache/275x275-75-76a8495b1514b8385f090381edf21f64a6c71d2f15c14e0eadabbfce2824fe9a.jpg', 
            ['file_date'] => '1497471650'
        ),
        ['94-1234.jpg'] => Array ( 
            ['file_title'] => '94-1234', 
            ['file_path'] => 'gallery-images-1435/94-1234.jpg', 
            ['thumb_path'] => 'resources/cache/275x275-75-6e20bd7f6644db1c0fa36600d2aa298b6a5d11e578113f9015fd90dc6b7390e5.jpg', 
            ['file_date'] => '1497470721'
        )
    )
);

谢谢。

2 个答案:

答案 0 :(得分:0)

您可以使用usort(),live demo

usort($array['images'], function($a, $b){return $b['file_date'] - $a['file_date'];});
print_r($array);

答案 1 :(得分:0)

仅对三维数组使用此函数。

Resources.Load

用法示例,

function array_sort($array, $on, $order=SORT_ASC){
    $new_array = array();
    $sortable_array = array();
    $flag=false;
    if (count($array) > 0) {
        foreach ($array as $k => $v) {
            if (is_array($v)) {
                foreach ($v as $k2 => $v2) {
                    if (is_array($v2)) {
                        foreach ($v2 as $k3 => $v3) {
                            if ($k3 == $on) {
                                $flag=true;
                                $sortable_array[$k][$k2] = $v2;
                            }
                        }
                    }
                }
            } else {
                $sortable_array[$k] = $v;
            }

            switch ($order) {
                case SORT_ASC:
                    isset($sortable_array[$k])?asort($sortable_array[$k]):'';
                    break;
                case SORT_DESC:
                    isset($sortable_array[$k])?arsort($sortable_array[$k]):'';
                    break;
            }
        }
    }
    return $flag===false?$array:$sortable_array;
}