Ethan Tabor
Ethan Tabor

Reputation: 21

PHP multidimensional array sort doesn't stick

I'm trying to sort a multidimensional array, but while the sort works within the loop, it doesn't save that sort after the loop has run. What do I need to do to make the sort stick?

    function cmp_by_orderNumber($a, $b) {
        return $a["ORDER"] - $b["ORDER"];
    }

    foreach($response['content']['listings'] as $i => $v) {
        usort($v['MEMBERS'], "cmp_by_orderNumber");

        // sorted!
        echo '<pre>'; print_r($v); echo '</pre>';
    }

    // sort has reverted!
    echo '<pre>'; print_r($response['content']['listings']); echo '</pre>';

Upvotes: 1

Views: 84

Answers (1)

bwoebi
bwoebi

Reputation: 23787

You need to iterate over the array by reference.

foreach($response['content']['listings'] as &$v) { // see the little & sign here
    usort($v['MEMBERS'], "cmp_by_orderNumber");

    // sorted!
    echo '<pre>'; print_r($v); echo '</pre>';
}

If you don't the subarray is copied and you change the copy, but not the original.

Upvotes: 5

Related Questions