【问题标题】:how do i sort the following array/stdclass object in php? [duplicate]如何在 php 中对以下数组/stdclass 对象进行排序? [复制]
【发布时间】:2011-01-09 22:40:28
【问题描述】:

如何在 php 中通过 'pos' 对这个对象进行排序?

Array ( 
[0] => stdClass Object ( [str] => Mondays [pos] => 170 ) 
[1] => stdClass Object ( [str] => Tuesdays [pos] => 299 )
[2] => stdClass Object ( [str] => Wednesdays [pos] => 355 )
[3] => stdClass Object ( [str] => Thursdays [pos] => 469 )
[4] => stdClass Object ( [str] => Fridays [pos] => 645 )
[5] => stdClass Object ( [str] => Mondays [pos] => 972 )
[6] => stdClass Object ( [str] => Tuesdays [pos] => 1033 ) 
[7] => stdClass Object ( [str] => Thursdays [pos] => 1080 )
[8] => stdClass Object ( [str] => Fridays [pos] => 1180 ) 

)

【问题讨论】:

  • 你想按什么对数组进行排序?字符串?位置?

标签: php arrays object sorting stdclass


【解决方案1】:

您可能可以使用usort() 系列函数在strpos 上对其进行排序。您必须为此定义自己的比较函数。

伪 PHP 示例:

function compareItems($a, $b)
{
    if ( $a->pos < $b->pos ) return -1;
    if ( $a->pos > $b->pos ) return 1;
    return 0; // equality
}

uasort($yourArray, "compareItems");

根据您的需要,other comparison functions 可能更合适。

【讨论】:

    【解决方案2】:

    试试这个功能

    function objSort(&$objArray,$indexFunction,$sort_flags=0) {
        $indices = array();
        foreach($objArray as $obj) {
            $indeces[] = $indexFunction($obj);
        }
        return array_multisort($indeces,$objArray,$sort_flags);
    }
    

    【讨论】:

    • 或许稍微解释一下会有帮助?
    猜你喜欢
    • 2012-06-23
    • 1970-01-01
    • 2011-12-30
    • 1970-01-01
    • 2020-05-18
    • 1970-01-01
    • 2021-08-17
    • 2019-11-02
    相关资源
    最近更新 更多