在PHP中递归地分解数组

时间:2012-10-25 04:43:23

标签: php arrays json

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

如何从数组中删除任何名为ServiceCurrentlyPlaying的内容? (来自json_decode(file, TRUE))对于知道它的人来说,这可能是一个简单的问题,但我一直在尝试做一些不涉及手动将每个数组硬编码到另一个空数组中的事情(就像有很多{{ 1}}是我正在做的事情,但由于嵌套量不同而有问题)

注意:我必须处理大约41958个文件,这些文件都有不同的嵌套级别,不同的数量和结构,所以..

结果我想:

foreach ($outer as $inner)

非常感谢,非常感谢。

2 个答案:

答案 0 :(得分:0)

USE

 $array=json_decode($jsondata);
    $i=0;
    foreach($array as $key=>$arr)
    {
     $out[$i]['fn']=$arr['fn'];
    $out[$i]['apps]=$arr['apps']['ServiceCurrentlyPlaying']

    $i++;
    }

答案 1 :(得分:0)

可能没有完全优化,但这是个主意。

$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;
  }
}
相关问题