在4级数组中对章节进行排序

时间:2019-01-23 10:22:05

标签: php arrays sorting multidimensional-array

我想将现有数组排序为4维数组: 我拥有的“列表”数组:

  1 => "text1"
  10 => "text10"
  11 => "text11"
  101 => "text101"
  1011 => "text1011"
  10123 => "text10123" 
  2 => "text2"
  20 => "text20"
  201 => "text201"
  2011 => "text2011"
  20111 => "text20111"

我想要的数组是一个按所有数字排序的数据(4维),我的意思是我在$ chapter [1]的末尾不会包含另一个包含10123 =>“ text10123”的数组(此代码将与该代码位于同一数组中:1011 =>“ text1011” 这是我想要的数组的一个例子

$chapter[1] = array(
  1 => "text1", array(
    10 => "text10", 11 => "text11", array(
      101 => "text101", array(
          1011 => "text1011", 10123 => "text10123" )
    )
  )
);

1 个答案:

答案 0 :(得分:0)

我想您可以使用for-loop并将每个数字分解为数字(用str-split),然后添加数组。

考虑以下示例:

$arr = array(1, 11, 111, 113, 2, 21, 211, 213);
$chapter = array(); // this will be your result array

foreach($arr as $e) {
    $digits = str_split($e);
    $current = &$chapter;
    foreach($digits as $d) {
        if (!isset($current[$d]))
            $current[$d] = array();
        $current = &$current[$d];
    }
}

注意,我使用&将新数组分配给原始结果之一。

我知道您的数组缺少键,不必进行排序,但是我想您可以克服它(之前对数组进行过滤和排序)

已编辑

问题更改后,这是示例代码:(当键DATA用于所需的文本,而键CHILDREN用于下一元素时)

$arr = array(1 => "text1", 10 => "text10", 11 => "text11", 101 => "text101", 1011 => "text1011", 10123 => "text10123", 2 => "text2", 20 => "text20", 201 => "text201", 2011 => "text2011", 20111 => "text20111");
$chapter = array();

foreach($arr as $key => $val) {
    $digits = str_split(substr($key, 0, 4)); // if 4 digits is the max depth 
    $current = &$chapter;
    foreach($digits as $d) {
        if (!isset($current["CHILDREN"][$d]))
            $current["CHILDREN"][$d] = array();
        $current = &$current["CHILDREN"][$d];
    }
    $current["DATA"] = $val;
}
相关问题