PHP基于其他对象属性对对象数组进行排序

时间:2012-01-30 17:41:23

标签: php sorting

我有一个Town对象数组,然后是另一个对象(City),它包含第一个对象的排序。

Class City
{
   $id
   $name
   $towns
   $town_id_order
   //etc
}

   Class Town
    {
        $id
        $name
        //etc
    }

所以我需要能够根据City-> town_id_order对城镇进行排序

我猜这是usort但是我无法将其作为排序使用对象。

这是我尝试过的,但返回'Expects array not string'

function cmp($a, $b)
    {
        if ($a == $this->towns) {
            return 0;
        }
        return ($a < $this->towns) ? -1 : 1;
    }

    $a = $this->getTownsOrder();

    usort($a, "cmp");

2 个答案:

答案 0 :(得分:1)

function cmp($a, $b)
{
    if ($a->towns == $b->towns) {
        return 0;
    }
    return ($a->towns < $b->towns) ? -1 : 1;
}

我正在尝试了解您的代码,但我认为上述代码可以正常工作。

答案 1 :(得分:1)

简单的foreach将满足您的需求。

$ret = array();
$town_id_order = $city->town_id_order;
foreach ($towns as $town) {
    $ret[array_search($town->id, $town_id_order)] = $town;
}
相关问题