PHP - Foreach循环和资源 [英] PHP - Foreach loops and ressources

查看:145
本文介绍了PHP - Foreach循环和资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了一个foreach循环来处理大量的项目,不幸的是它使用了大量的内存。 (可能是因为它正在做一个数组的副本)。
显然有一种方法可以用下面的代码保存一些内存: $ items =& $ array;



代替循环是否更好?



有没有办法销毁每一个项目,只要他们已经在一个foreach循环处理。

例如

  $ items =& $ array; 
foreach($ items为$ item)
{
dosomethingwithmy($ item);
destroy($ item);



$ b $ p
$ b我只是寻找处理大量项目的最佳方法,用完了

解决方案

为循环尝试一个 p>

  $ keys = array_keys($ array); ($ i = 0,$ n = count($ keys); $ i< $ n; ++ $ i){
$ item =& $ array [$ keys [$ i] ]。
dosomethingwithmy($ item);
destroy($ item);
}


I'm using a foreach loop to process a large set of items, unfortunately it's using alot of memory. (probably because It's doing a copy of the array). Apparently there is a way to save some memory with the following code: $items = &$array;

Isn't it better to use for loops instead?

And is there a way to destroy each item as soon as they have been processed in a foreach loop.

eg.

    $items = &$array;
    foreach($items as $item)
    {
     dosomethingwithmy($item);
     destroy($item);
    }

I'm just looking for the best way to process a lot of items without running out of ressources.

解决方案

Try a for loop:

$keys = array_keys($array);
for ($i=0, $n=count($keys); $i<$n; ++$i) {
    $item = &$array[$keys[$i]];
    dosomethingwithmy($item);
    destroy($item);
}

这篇关于PHP - Foreach循环和资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆