温馨提示:本文翻译自stackoverflow.com,查看原文请点击:其他 - Parsing PHP Multidimensional Array
php

其他 - 解析PHP多维数组

发布于 2020-03-27 11:13:42

这里(下面给出)是我正在做的一些非常简单的php解析多维数组的东西。我只是在搜索“突出显示”键,然后将一些键值对存储在另一个数组中。有什么更好的方法可以实现这一目标(我是指性能),而不是有n个foreach循环来实现所需的目标。

$json_O=json_decode(file_get_contents($url),true);
     foreach($json_O as $section1=>$items1){
        if($section1==highlighting){
            foreach($items1 as $section2=>$items2){
                    $key=$section2;
                    foreach($items2 as $section3=>$items3){
                        foreach ($items3 as $section4=>$items4){
                            $value=$items4;
                            $found[]=array('Key' => $key, 'Value' => $value);

这是我尝试解析的示例php对象:

Array
(
    [responseHeader] => Array
        (
            [status] => 0
            [QTime] => 3
            [params] => Array
                (
                    [indent] => on
                    [start] => 0
                    [q] => russian
                    [fragsize] => 40
                    [hl.fl] => Data
                    [wt] => json
                    [hl] => on
                    [rows] => 8
                )

        )

    [response] => Array
        (
            [numFound] => 71199
            [start] => 0
            [docs] => Array
......
......
    [highlighting] => Array
        (
            [114360] => Array
                (
                    [Data] => Array
                        (
                            [0] => AMEki has done it better <em>russian</em>...

....
....

现在有两件事:1)我可以更快吗?2)我可以设计得更好吗?

查看更多

查看更多

提问者
avinash shah
被浏览
194
goat 2012-04-28 23:40

这似乎是不必要的

 foreach($json_O as $section1=>$items1){
    if($section1==highlighting){
        foreach($items1 as $section2=>$items2){

你可以做

        foreach($json_O['highlighting'] as $section2=>$items2){

尽管未经测试,也可以简化其余部分

$riter = new RecursiveArrayIterator($json_O['highlighting']);
$riteriter = new RecursiveIteratorIterator($riter, RecursiveIteratorIterator::LEAVES_ONLY);
$found = array();
foreach ($riteriter as $key => $value) {
    $key = $riteriter->getSubIterator($riteriter->getDepth() - 2)->key();
    $found[] = compact('key', 'value');
}

就个人而言,我只是使用嵌套的foreach循环。这很容易理解,而我对递归迭代器的创造性使用却不是。