简体   繁体   English

按索引对stdClass对象排序

[英]Sort stdClass object by its index

I've seen a million similar questions on stackoverflow but none of them, that I can find, deal with sorting the actual index value of the object. 我已经在stackoverflow上看到了上百万个类似的问题,但是我找不到它们可以对对象的实际索引值进行排序。

I have a standard object that I've given a value ($vid) to sort instead of it populating incrementally itself. 我有一个标准对象,我给它提供了一个值($ vid)进行排序,而不是自己增量填充。

foreach ($array_videos as $v) {
            $govideo = $this->staff_model->get_video($v->vid);
            $goforit[$v->vid] = $vimeo->call('vimeo.videos.getInfo', array('video_id' => $govideo->video_id));
}

When I do this I receive the following output: 当我这样做时,我收到以下输出:

[33] => stdClass Object ...
[12] => stdClass Object ...
[55] => stdClass Object ...
[61] => stdClass Object ...

I would like to sort this array of objects by the object index, ASC or DESC. 我想按对象索引,ASC或DESC对这个对象数组进行排序。 For example: 例如:

[61] => stdClass Object ...
[55] => stdClass Object ...
[33] => stdClass Object ...
[12] => stdClass Object ...

I've tried ksort and some various usort functions. 我试过ksort和一些各种usort函数。 Can't seem to wrap my head around this. 似乎无法解决这个问题。

Any help would be appreciated. 任何帮助,将不胜感激。

ksort() will do the trick: ksort()将达到目的:

ksort($array_videos);

ksort will sort the array keys in ASC . ksort将对ASC的数组键进行排序。 you could quickly reverse the order using array_reverse() : 您可以使用array_reverse()快速反转顺序:

$array_videos = array_reverse($array_videos);

for your real world example you could do one of the following: 对于您的真实示例,您可以执行以下操作之一:

foreach (ksort($array_videos) as $v)

or 要么

foreach (array_reverse(ksort($array_videos)) as $v)

Better Yet!! 更好! to reverse the sort to DESC as per the recommendations by Jim , you can use krsort() : 按照Jim的建议将排序反转为DESC ,可以使用krsort()

ksort($array_videos); //ASC
krsort($array_videos); //DESC

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

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