通过键的存在对多维数组进行排序

时间:2016-01-01 13:05:20

标签: php arrays sorting multidimensional-array

我有阵列:

Array (
    [0] => Array (
        [var_for_type] => inside
        [show_about] => on
        [pagethumb] => on
        [postthumb] => on
        [portfoliothumb] => on
    )
    [1] => Array (
        [var_for_type] => shadow
        [show_about] => on
        [box_for_type] => Array ( [0] => cvb [1] => odf [2] => o-koshkah )
        [postthumb] => on
    )
)

我需要通过键' box_for_type'来存储它。如果键' box_for_type'存在,而不是在多维数组中的其他数组之前输出它。我该怎么办?

1 个答案:

答案 0 :(得分:1)

您需要使用usort()函数来定义自己的比较元素的函数:

 $sample = [
   ['test' => 'a'],
   ['test' => 'g', 'box_for_type' => []],   
   ['test' => 'b'],
   ['test' => 'c', 'box_for_type' => []],
 ];


usort($sample, function ($a, $b){
   return (int)!array_key_exists('box_for_type', $a); 
});

print_r($sample);
相关问题