dpnof28482 2012-10-25 04:43
浏览 23
已采纳

在PHP中递归地分解数组

{ 
    "ServiceCurrentlyPlaying": {
        "fn": "Slideshow-41958.mp4",
        "apps": {
            "ServiceCurrentlyPlaying": {
                "state": "stopped"
            }
        }
    }
}

How would I break anything named ServiceCurrentlyPlaying out of an array? (from json_decode(file, TRUE)) This is probably an easy question to anyone that knows it, but I've been trying to do something that doesn't involve manually hardcoding each array into another empty array (like with a lot of foreach ($outer as $inner) is what I'm doing but having issues since the amount of nesting varies)

Note: I have to deal with around 41958 files that all have different levels of nesting, different amounts and structure, so ..

Result I'd like would be:

{
    "fn": "Slideshow-41958.mp4",
    "apps": {
    "state": "stopped"
    }
}

Thanks, very much appreciated.

  • 写回答

2条回答 默认 最新

  • dongpang2483 2012-10-25 05:20
    关注

    Not quite optimized maybe, but this is the idea.

    $data = json_decode('{ "ServiceCurrentlyPlaying": { "fn": "Slideshow-41958.mp4", "apps": { "ServiceCurrentlyPlaying": { "state": "stopped" } } } }', true);
    $modifiedData = breakArray($data);
    
    function breakArray($arr) {
      if(is_array($arr) && sizeof($arr)>0) {
        $buffer = array();
    
        foreach($arr as $key=>$value) {
          if($key==="ServiceCurrentlyPlaying") {
            if(is_array($value)) $buffer = array_merge($buffer, breakArray($value));
          } else {
            $buffer[$key] = (is_array($value) ? breakArray($value) : $value);
          }
        }
    
        return $buffer;
      } else {
        return $arr;
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容