Harea Costicla Harea Costicla - 5 months ago 54
PHP Question

Recursive ksort : not sort the array

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

Answer

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;
}
Comments