【问题标题】:sorting chapters in an 4 level array在 4 级数组中对章节进行排序
【发布时间】:2019-01-23 10:22:04
【问题描述】:

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

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

我想要的数组是一个所有数据都按每个数字排序的数组(4 维) (这个将与这个在同一个数组中:1011 =>“text1011” 这是我想要的数组的一个例子

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

【问题讨论】:

  • 请添加有关您的问题的更多信息,并添加您尝试过的内容。
  • 您好,请查看本指南how to ask good questions。您缺少不起作用的代码。如果您希望免费解决您的问题,那不是堆栈溢出的目的。
  • 更准确地说:1.更详细地描述您需要的结果,您显示的示例描述性不够,并且包含错​​误; 2. 展示你尝试过的东西; 3. 描述你的尝试是如何失败的。在这种情况下,问题将被视为高质量问题,其他用户将很乐意提供帮助

标签: php arrays sorting multidimensional-array


【解决方案1】:

我猜你可以使用 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;
}

【讨论】:

  • 非常感谢,但是您如何为每个键分配值 1 将拥有例如 House 和 111 Car
  • 赋值是什么意思?你能用期望的输出更新你的问题吗?目前它在您的问题中发布的作品
  • 您意识到这与原始帖子非常不同,对吧?并且键不能有两个值,因此您的期望输出无效-因为键“1”不能同时具有“text1”和其余数组-仅当它们也封装在数组下时...
  • 是的,我的意思是它们封装在数组下。数组下有一个数组作为数字的排序
  • @jason9 通过您的更新编辑了答案 - 请同时编辑您的问题的标题 - 目前没有描述问题
猜你喜欢
  • 1970-01-01
  • 2021-08-04
  • 1970-01-01
  • 2020-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-09
相关资源
最近更新 更多