質問

I have a large array (this is just a section of it):

[0] => stdClass Object
    (
        [products] => Array
            (
                [0] => stdClass Object
                    (
                        [body_html] => bodyhtml
                        [published_at] => 2012-12-16T23:59:18+00:00
                        [created_at] => 2012-12-16T11:30:24+00:00
                        [updated_at] => 2012-12-18T10:52:14+00:00
                        [vendor] => Name
                        [product_type] => type
                    )
                [1] => stdClass Object
                    (
                        [body_html] => bodyhtml
                        [published_at] => 2012-12-16T23:59:18+00:00
                        [created_at] => 2012-12-16T10:30:24+00:00
                        [updated_at] => 2012-12-18T10:52:14+00:00
                        [vendor] => Name
                        [product_type] => type
                    )
              )
      )

and I need to arrange each of the products by the date they where created... I've tried and failed all kinds of usort, ksort, uksort techniques to try and get it to be in a specific order (chronological) but failed!

any guidance would be most appreciated

役に立ちましたか?

解決

You'll need to use the uasort function, which lets you specify a simple comparison function you write. See uasort for specifics. You can also define an anonymous function as part of the uasort call. Since you have an object with an array, make sure that you are passing the object's array to the uasort function. Since you're sorting an array of objects, your comparison function should take into account that it's working with 2 objects.

Building upon your responses and your var_dump:

uasort($foo[0]->products, function($a, $b) {

    if ($a->created_at < $b->created_at) {
        return -1;
    }
    return 1;
});

他のヒント

Here is an example:

$arr_1 = array('name' => 'A', 
               'date' => '2012-12-16T11:30:24+00:00' , 
               'created_at' => '2012-12-16T11:30:24+00:00');
$arr_2 = array('name' => 'B', 
               'date' => '2012-12-16T11:30:22+00:00' , 
               'created_at' => '2012-12-16T11:30:21+00:00');


$test_array = array($arr_1, $arr_2);
var_dump($test_array);

usort($test_array, function($a, $b) {
    $a_date = new DateTime($a['date']);
    $b_date = new DateTime($b['date']);
    if ($a_date < $b_date) {
        return -1;
    }
    return 1;
});

var_dump($test_array);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top