简体   繁体   English

使用php加速递归foreach

[英]Speed up recursive foreach using php

I am running this against an associative (non-numerical keys) array that is 80K lines, decoded from a 2.1K json file:我正在针对一个 80K 行的关联(非数字键)数组运行它,从 2.1K json 文件解码:

$ret = array();

function recursive(array $array, $tableName, $level=''){

global $ret;

$tableData = array();

    foreach($array as $key => $value){
        if(!is_array($key)) $k = $key;  // keep array keys for tablename

        if(is_array($value)){
            $key = is_int($key) ? $tableName : $key; //skip empty subarrays
            recursive($value, $level=$key);

        } else{
            $tableData=[$tableName, $k, $value];
        }
        if (!empty($tableData))
        {array_push($ret, $tableData);
        }

    }
 return $ret;
}

$ret =(recursive($array, 'project'));

The json data contains empty sub-arrays which are discarded during the 'is_int($key) recursive loop. json 数据包含在 'is_int($key) 递归循环期间被丢弃的空子数组。 This is a typical file size that will be processed and the function is taking over 2 mins to run - which may be as good as it gets - but I wanted to ask if there were any ways to speed this function up by better coding.这是将被处理的典型文件大小,该函数运行需要 2 多分钟 - 这可能已经足够了 - 但我想问问是否有任何方法可以通过更好的编码来加速这个函数。

thank you,谢谢你,

It seems to be always true: if(!is_array($key)) $k = $key;似乎总是正确的: if(!is_array($key)) $k = $key;

You are don't use the $level variable.您不使用$level变量。 Why do you need it?你为什么需要它?

Globals are really bad idea.全球性真的是个坏主意。 You probably need to send variables to your function by link instead of value:您可能需要通过链接而不是值将变量发送到您的函数:

function recursive(&$data, &$result, $tableName)
{
    //some of your logic here
    //...
    //if you need a recursion call
    recursive($data, $result, $tableName);
}

//function call
$result = [];
recoursive($data, $result, 'project');

//all of your data now in the result variable

Also it may be a good idea to read and process your data by chunks.此外,按块读取和处理数据可能是个好主意。 Iterators or generators can help you with this.迭代器生成器可以帮助您解决这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM