duanlou7910 2015-12-21 10:00
浏览 64

从字符串爆炸中递归创建多维数组

I have an array containing a lot category strings like

Cars > Model1
Cars > Model1 > Accessories
Cars > Model1 > Something
Cars > Model2
Cars > Model3

which I want to recursively transform into a multidimensional array where "Cars" is the parent element of Model1, Model2 and Model3.

And of course, "Accessories" and "Something" would be child elements of Model1.

Have been trying to work out the logic behind this for quite some time now, and I just can't seem to figure it out...

Edit: What I have so far, it's not much. As mentioned, can't seem to figure out the logic behind how to develop this.

$array = array(
        'Cars > Model1',
        'Cars > Model1 > Accessories',
        'Cars > Model1 > Something',
        'Cars > Model2',
        'Cars > Model3'
    );

    for ($i = 0; $i < count($array); $i++) {
        $name = explode('>', $array[$i]);

        // somehow check if the current "name" is already pushed to a new array - if it is, then add as a child.
    }
  • 写回答

1条回答 默认 最新

  • doulu2591 2015-12-21 11:23
    关注

    Here's how you can achieve this

    $array_data = array(
        'Cars > Model1',
        'Cars > Model1 > Accessories',
        'Cars > Model1 > Something',
        'Cars > Model2',
        'Cars > Model3'
    );
    
    $last_key = null;
    $array = [];
    $result = [];
    foreach($array_data as $key => $values)
    {
      $data = explode('>', $values);
      if(is_array($data))
      {
        $count = 0;
        $pop = array_pop($data);
        foreach($data as $k => $v)
        {
            if($count == 1)
            {
                unset( $result[$last_key] );
                $result[$last_key][$v] = $pop;
                $count++;
                continue;
            }
            $last_key = $v;
            $result[$v] = $pop;
            $count++;
        }
        $array[] = $result;
      }
     }
    

    and the result will be something like

    echo '<pre>';print_r( $array );
    Array
    (
      [0] => Array
        (
            [Cars ] =>  Model1
        )
    
    [1] => Array
        (
            [Cars ] => Array
                (
                    [ Model1 ] =>  Accessories
                )
        )
    
     [2] => Array
        (
            [Cars ] => Array
                (
                    [ Model1 ] =>  Something
                )
    
        )
    
    [3] => Array
        (
            [Cars ] =>  Model2
        )
    
    [4] => Array
        (
            [Cars ] =>  Model3
        )
    
     )
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services