s-6ren">
gpt4 book ai didi

php - 如何在php中对对象进行排序?

转载 作者:行者123 更新时间:2023-12-02 01:14:04 25 4
gpt4 key购买 nike

我有一个属性 $this->result 包含一个对象:

array(40) {
[0] => object(Model)#181 (7) {
["_id":protected] => string(2) "1"
["_img":protected] => string(95) "/1273720855.jpg"
}
[1] => object(Model)#224 (7) {
["_id":protected] => string(2) "2"
["_img":protected] => string(95) "/test.jpg"
}
[2] => object(Model)#182 (7) {
["_id":protected] => string(2) "3"
["_img":protected] => string(95) "/127377775.jpg"
}
[3] => object(Model)#224 (7) {
["_id":protected] => string(2) "4"
["_img":protected] => string(95) "/test.jpg"
}
[4] => object(Model)#182 (7) {
["_id":protected] => string(2) "5"
["_img":protected] => string(95) "/129586775.jpg"
}
...

所以如果我做一个循环,我可以获得 img 属性:

foreach($this->result as $val){
echo $val->getImg(); //'/1273720855.jpg'
}

我想做的是对对象进行排序,使具有 /test.jpg 的属性排在最后或最后回显它们,例如:

array(40) {
[2] => object(Model)#182 (7) {
["_id":protected] => string(2) "3"
["_img":protected] => string(95) "/127377775.jpg"
}
[4] => object(Model)#182 (7) {
["_id":protected] => string(2) "5"
["_img":protected] => string(95) "/129586775.jpg"
}
[1] => object(Model)#224 (7) {
["_id":protected] => string(2) "2"
["_img":protected] => string(95) "/test.jpg"
}
[3] => object(Model)#224 (7) {
["_id":protected] => string(2) "4"
["_img":protected] => string(95) "/test.jpg"
}
....

我对任何解决方案都感兴趣,即使我必须创建一个可以对后记等进行排序的新数组

Ant 的想法?谢谢

最佳答案

你所追求的是 usort。

http://php.net/usort

bool usort ( array &$array , callable $cmp_function )

您编写运行排序的函数,并将此函数作为参数 2 传递。然后 PHP 将遍历数组并对数组中的每个值运行该函数。

所以你应该有类似这样的东西:

<?php
function cmp($a, $b)
{
return strcmp($a->getImg(), $b->getImg());
}

usort($this->result, "cmp");

关于php - 如何在php中对对象进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13732274/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com