2

I have a question So I have this array :

Array
(
[2016] => Array
    (
        [23] => Array
            (
                [total_auctions] => 0
                [total_price] => 0
            )

        [22] => Array
            (
                [total_auctions] => 0
                [total_price] => 0
            )

        [21] => Array
            (
                [total_auctions] => 0
                [total_price] => 0
            )

        [20] => Array
            (
                [total_auctions] => 0
                [total_price] => 0
            )
)

I want to sort recursive by key. So I create the methode :

 public function sortNestedArrayAssoc($a)
{
    if (!is_array($a)) {
        return false;
    }
    ksort($a);
    foreach ($a as $k=>$v) {
        $this->sortNestedArrayAssoc($a[$k]);
    }
    return true;
}

But I get the same result, the array with the key 23 is the first and I don' really understand where is the problem. Can you help me please ? Thx in advance and sorry for my english

Harea Costicla
  • 797
  • 3
  • 9
  • 20

1 Answers1

11

As John Stirling mentioned, something you could do would be to pass your arguments by reference. You can do this by using the & operator in your method argument. The syntax for that would be (with the only change being the first line):

public function sortNestedArrayAssoc(&$a)
{
    if (!is_array($a)) {
        return false;
    }
    ksort($a);
    foreach ($a as $k=>$v) {
        $this->sortNestedArrayAssoc($a[$k]);
    }
    return true;
}

This means that you are then passing the variable into your function and modifying it directly instead of what PHP does normally which is pass a copy of the variable into your function. ksort is an example of a function that uses a pass by reference in its function definition.

If you were strongly against using pass by reference, you'd have to modify your code to return your variable/array to the calling scope where you then update your array.

public function sortNestedArrayAssoc($a)
{
    if (is_array($a)) {
        ksort($a);
        foreach ($a as $k=>$v) {
            $a[$k] = $this->sortNestedArrayAssoc($v);
        }
    }
    return $a;
}
Community
  • 1
  • 1
MasterOdin
  • 7,117
  • 1
  • 20
  • 35
  • What would be the benefit to pass it by reference instead of value? – SML Jun 09 '16 at 15:51
  • Preference for the most part. You'll save on memory usage by using pass by reference (as PHP doesn't have to make a copy of your variable, it'll just modify it in place). – MasterOdin Jun 09 '16 at 15:53
  • thanks for your reply. It seems that pass by reference is slower in performance so I just wasn't sure when to use it. http://stackoverflow.com/questions/178328/in-php-5-0-is-passing-by-reference-faster – SML Jun 09 '16 at 16:04