按键值对PHP中对象数组的数组进行排序 [英] Sorting an array of an array of objects in PHP by key value

查看:35
本文介绍了按键值对PHP中对象数组的数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我有如下设置:

Array ( 
[0] => Array ( [0] => stdClass Object ( [nid] => 1 [title] => title1 [uid] => 1 [parent] => 0 [weight] => -15 [name] => name1 [value] => 0 )
               [1] => stdClass Object ( [nid] => 2 [title] => title2 [uid] => 1 [parent] => 0 [weight] => -7 [name] => name2 [value] => 100 )
               [2] => stdClass Object ( [nid] => 3 [title] => title3 [uid] => 2 [parent] => 0 [weight] => -1 [name] => name3 [value] => 0 )
               [3] => stdClass Object ( [nid] => 4 [title] => title4 [uid] => 2 [parent] => 0 [weight] => 1 [name] => name4 [value] => 80 )
              )
  )

我需要的是一种通过对象中的 [value] 键对父数组中的所有数组进行排序的方法.我已经用 usort 和不同的方法尝试了大约 2 天,但我似乎无法理解它.[value] 键的范围是 0 到 100,我需要按降序排列所有数组(即:100 到 0).

What I need is a way to sort all the arrays inside the parent array by the [value] key in the Object. I've been trying for about 2 days now with usort and different methods but I just can't seem to get my head around it. The [value] key will range anywhere from 0 to 100 and I need all of the arrays sorted in decreasing order (IE: 100 down to 0).

推荐答案

使用 usort:

function cmp($a, $b) {
  if ($a->value == $b->value) {
    return 0;
  } else {
    return $a->value < $b->value ? 1 : -1; // reverse order
  }
}

usort($arr, 'cmp');

这篇关于按键值对PHP中对象数组的数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆