简体   繁体   English

如何将具有特定属性的项目移到PHP数组的顶部

[英]How can I move an item with a specific property to the top of a PHP array

I have an associative array that looks like so: 我有一个看起来像这样的关联数组:

   {
      "album_6":{
        "name":"02-04-2014",
        "id":6,
        "count":"2",
        "cover":"26974771533c4b57cb0aa"
      },
      "album_3":{
        "name":"Photos of you",
        "id":3,
        "count":"4",
        "cover":"8872935615302242c4fa6c",
        "of_you":true
      }
    }

Thy array can contain many items but one of the items will have the extra property of_you . 您的数组可以包含许多项目,但是其中一项将具有额外的属性of_you

In the above example it is album_3 在上面的示例中,它是album_3

I would like to move the item that has the of_you property to the first position in the array. 我想将具有of_you属性的项目移到数组中的第一个位置。 How can I achieve this? 我该如何实现?

I have tried using usort with a comparison function but it doesn't seem to work. 我尝试将usort与比较功能一起使用,但似乎无法正常工作。

Note: The item could be at any numerical index. 注意:该项目可以是任何数字索引。

ANSWER: 回答:

I found the answer literally straight after posting this question. 发布此问题后,我从字面上直接找到了答案。 The solution is as follows: 解决方法如下:

  uasort($albums, function($a, $b) {
      return (empty($a['of_you'])) ? 1 : -1;
  });

If anyone has a faster/more efficient method. 如果有人有更快/更有效的方法。 Please post it as an answer and I will accept. 请发布它作为答案,我会接受。

EDIT: in order to mantain the associative keys asort() is a better choice in this instance 编辑:为了维护关联键asort()在这种情况下是更好的选择

Even if it didn't work for you, usort is the way: 即使对您不起作用,使用usort也可以:

usort($array, function($a, $b) {
    $hasA = array_key_exists('of_you', $a);
    $hasB = array_key_exists('of_you', $b);

    if ($hasA and $hasB) {
        return 0;
    }

    return $hasA ? -1 : 1;
});

Keep in mind, it will not do more sort than first the elements with the key of_you and then the rest. 请记住,与首先使用键of_you的元素然后进行其余操作相比,它不会做更多的排序。

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

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