简体   繁体   English

有没有更好的方法来过滤关联数组?

[英]Is there a better way to filter an associative array?

Trying to sort my array to show the group with meat categoryName to be first element in array.试图对我的数组进行排序以显示带有肉 categoryName 的组是数组中的第一个元素。 Is there a better way to sort this array than running two for loops?有没有比运行两个 for 循环更好的方法来对这个数组进行排序? My array looks like this我的阵列看起来像这样

Array
(
    [0] => Array
        (

            [categoryId] => C4ye95zr403cx9wqi11eo
            [categoryName] => set
            [categoryStatus] => true
        )

    [1] => Array
        (

            [categoryId] => Cj-v2b7szu3jpph1rvu03
            [categoryName] => meat
            [categoryStatus] => true
        )

I want to rearrange the array by categoryName == meat to be first element in array.我想按 categoryName == meat 重新排列数组,使其成为数组中的第一个元素。

Currently i'm just running two loops to do this.目前我只是运行两个循环来做到这一点。

$temp = array();
foreach($array as $k => $v)
            {
                if($v['categoryName']=="meat")
                {
                    $temp[]     = $menu[$k];
                    $setEmpty   = false;
                    unset($array[$k]);
                }
            }
            foreach($menu as $k=>$v)
            {
                $temp[] = $array[$k];
            }

You can utilize usort :您可以使用usort

usort($array, function ($element) {
    return $element['categoryName'] === 'meat' ? 0 : 1;
});

The documentation states the following about the callback:文档说明了有关回调的以下内容:

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.如果第一个参数被认为分别小于、等于或大于第二个参数,则比较函数必须返回一个小于、等于或大于零的整数。

So, in order to push the meat category to the beginning, all you need to do is say that everything else is greater than it.因此,为了将meat类别推向一开始,您需要做的就是说其他一切都比它大。

You can check the fiddle for a test.您可以检查小提琴进行测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM