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


Sort multidimensional array by existence of key

我有数组:

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"存在,则在多维数组中的其他数组之前输出它。我该怎么做?

您需要使用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);