通过排序键值对象数组的PHP中的数组 [英] Sorting an array of an array of objects in PHP by key value
本文介绍了通过排序键值对象数组的PHP中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
基本上我有类似下面的设置:
Basically I have a setup like the following:
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 )
)
)
我需要的是一种通过在对象的[值]键父阵列内所有的阵列进行排序。我一直在想,现在约2天usort和不同的方法,但我似乎无法让我的头周围。 [数值]键从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屋!
查看全文