PHP 数组排序键 [英] PHP array sort keys

查看:46
本文介绍了PHP 数组排序键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的多数组,如下所述,我需要按其键标签(而不是键值)进行排序.

I've a simple multi array as described below that I need to order by its key label (not by key value).

array(
    1 => array(
        2 => array();
        11 => array();
        20 => array();
        31 => array();
        4 => array();
        43 => array();
        12 => array();
        3 => array();
    );
    2 => array();
    11 => array();
    20 => array();
    31 => array();
    4 => array();
    43 => array();
    12 => array();
    3 => array(); );

问题是我的排序返回了我的数组,排序如下:

The problem is that my ordering is returning my arrays ordered like:

1, 11, 12, 2, 20, 3, 31, 等等...而不是 1,2,3,4,11,12, 等等.

1, 11, 12, 2, 20, 3, 31, etc... And not 1,2,3,4,11,12, etc..

这是我的订购功能:

private function orderByKey(&$array) {
        ksort($array);
        foreach($array as $value) {
            if (is_array($value)) {
                $this->orderByKey($value);
            }
        }
    }

这里可能有什么问题?

谢谢.

推荐答案

您需要访问 $value 作为对 $array 中条目的引用

You need to access $value as a reference to the entry in $array

private function orderByKey(&$array) {
        ksort($array);
        foreach($array as &$value) {
            if (is_array($value)) {
                $this->orderByKey($value);
            }
        }
    }

这篇关于PHP 数组排序键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆