[英]Sort multidimensional array by existence of key
I have 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
)
)
And I need to sort it by existence of key 'box_for_type'. 我需要按键“ box_for_type”的存在对其进行排序。 If key 'box_for_type' exists, than output it before other arrays in multidimensional array. 如果键'box_for_type'存在,则将其输出到多维数组中的其他数组之前。 How can I do it? 我该怎么做?
You need to use usort() function where you can define your own function for comparing elements: 您需要使用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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.