dtiopy6088 2016-08-19 10:34
浏览 68
已采纳

PHP删除无用的嵌套数组

I'm using jQuery plugin which generates following array:

    array:4 [
  0 => array:1 [
    "page_id" => "1"
  ]
  1 => array:2 [
    "page_id" => "2"
    "children" => array:1 [
      0 => array:2 [
        0 => array:2 [
          "page_id" => "10"
          "children" => array:1 [
            0 => array:2 [
              0 => array:1 [
                "page_id" => "12"
              ]
              1 => array:1 [
                "page_id" => "13"
              ]
            ]
          ]
        ]
        1 => array:1 [
          "page_id" => "11"
        ]
      ]
    ]
  ]
  2 => array:1 [
    "page_id" => "4"
  ]
  3 => array:1 [
    "page_id" => "3"
  ]
]

This array is dynamic so there can be more nested arrays. I need to clean array little bit. As you can see under page_id => 2 there is children. It contains one useless array (0 => array: 2).

Is it possible to remove this useless arrays? I really need it to regenerate my menu items positions... Any ideas?

  • 写回答

2条回答 默认 最新

  • dongle3217 2016-08-19 10:59
    关注

    You can use a recursive algorithm:

    function removeUselessArrays($array) {
        $newArray = [];
    
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                if (array_keys($value) === [ 0 ]) {
                    $newArray[$key] = removeUselessArrays($value[0]);
                } else {
                    $newArray[$key] = removeUselessArrays($value);
                }
            } else {
                $newArray[$key] = $value;
            }
        }
    
        return $newArray;
    }
    

    See the code working here.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数