基于嵌套对象属性对对象进行排序?

时间:2019-11-09 23:00:34

标签: php

给出这种可能的对象结构(通过var_dump):

stdClass Object
(
    [jobs] => Array
        (
            [0] => stdClass Object
                (
                    [id] => fbb3d
                    [title] => TRS Trainer
                    [full_title] => TRS Trainer - Moorhead
                    [shortcode] => 2330A8E687
                    [code] => 
                    [state] => published
                    [department] => CSD Contact Centers
                    [url] => https://csd.workable.com/jobs/1029739
                    [application_url] => https://csd.workable.com/jobs/1029739/candidates/new
                    [shortlink] => https://csd.workable.com/j/2330A8E687
                    [location] => stdClass Object
                        (
                            [country] => United States
                            [country_code] => US
                            [region] => Minnesota
                            [region_code] => MN
                            [city] => Moorhead
                            [zip_code] => 
                            [telecommuting] => 
                        )

                    [created_at] => 2019-05-21T21:03:39Z
                )
        )
)

通过var_export:

stdClass::__set_state(array(
   'jobs' => 
  array (
    0 => 
    stdClass::__set_state(array(
       'id' => 'fbb3d',
       'title' => 'TRS Trainer',
       'full_title' => 'TRS Trainer - Moorhead',
       'shortcode' => '2330A8E687',
       'code' => NULL,
       'state' => 'published',
       'department' => 'CSD Contact Centers',
       'url' => 'https://csd.workable.com/jobs/1029739',
       'application_url' => 'https://csd.workable.com/jobs/1029739/candidates/new',
       'shortlink' => 'https://csd.workable.com/j/2330A8E687',
       'location' => 
      stdClass::__set_state(array(
         'country' => 'United States',
         'country_code' => 'US',
         'region' => 'Minnesota',
         'region_code' => 'MN',
         'city' => 'Moorhead',
         'zip_code' => NULL,
         'telecommuting' => false,
      )),
       'created_at' => '2019-05-21T21:03:39Z',
    ))
  ),
))

按地区排序的最佳方法是什么?我尝试像这样使用usort:

function cmp($a, $b) {
    return strcmp($a->jobs->location->region, $b->jobs->location->region);
}
$response = json_decode($response);
usort($response, "cmp");

但是在将JSON响应解码为对象然后通过usort运行它之后,它就没有排序。我认为我做的不对,编码排序算法并不是我最强的专长。

我确实考虑过尝试sort,但是意识到由于嵌套对象的缘故,它不会削减它。我在Google上寻找其他示例来解决这个问题,但是似乎大多数选项都是针对数组的,而我正在使用一个对象。

1 个答案:

答案 0 :(得分:1)

正如您在注释中所解释的,您希望对作为主对象属性的数组进行排序。为此,您可以将该属性而不是整个对象传递给usort(),然后对比较$a->location->region进行排序。

function cmp($a, $b) {
    return strcmp($a->location->region, $b->location->region);
}
$response = json_decode($response);
usort($response->jobs, "cmp");