简体   繁体   English

递归ksort:不对数组排序

[英]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. 但是我得到了相同的结果,键为23的数组是第一个,我真的不知道问题出在哪里。 Can you help me please ? 你能帮我吗 ? Thx in advance and sorry for my english 提前谢谢,对不起我的英语

As John Stirling mentioned, something you could do would be to pass your arguments by reference . 正如约翰·斯特林(John Stirling)所说,您可以做的是通过引用传递您的论点 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. 这意味着您然后将变量传递给函数并直接对其进行修改,而不是PHP通常所做的将变量副本传递给函数的行为。 ksort is an example of a function that uses a pass by reference in its function definition. ksort是在函数定义中使用按引用传递的函数示例。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM