Php:数组嵌套循环性能

标签 php arrays loops

我有两个数组

$list = Array
([0] => stdClass Object
    (
        [id] => 10
        [data] => "test data"
    )
[1] => stdClass Object
...
...(max 3000 ~ 4000 items)

$attributes = Array
([0] => stdClass Object
    (
        [ids] => 11
        [list] => '<ul>...</ul>'
    )
[1] => stdClass Object
...
...(max 3000 ~ 4000 items)

我正试图加入他们,但我能写的唯一表现方式是可用

$nrrowslist = count($list);
for ($i = 0; $i < $nrrowslist; $i++){
  $nrat = count($attributes);
  for ($j = 0; $j < $nrat; $j++)
  {
    if($list[$i]->id == $attributes[$j]->ids){
      $list[$i]->attributes = $attributes[$j]->list;
      array_splice($attributes, $j, 1); // remove the item
      break; // since there is other item with that id 
    }
  }
}

//在~0.470 秒内完成

但是如果我写的话

foreach($list as $art){
  foreach($attributes as $attr){
    if($art->id == $attr->ids){
      $art->attributes = $attr->list;           
    }
  }
}

它在 ~ 5.500 秒内完成......而且太多了

我可以做些什么来执行更多的第一种方法情况?

最佳答案

通过两次迭代并在作业中使用公共(public)参数,您可能会取得一些成功

$newlist = array();

// I'm sure there's a better way to do this initial assignment
foreach($list as $row)
{
  $newlist[$row->id] = $row;
}

foreach($attributes as $attr)
{
  if(isset($newlist[$attr->ids]) === true)
  {
    $newlist[$attr->ids]->attributes = $attr->list;
  }
}

var_dump($newlist);

关于Php:数组嵌套循环性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34471273/

相关文章:

javascript - 使用 Promises 将元素推送到数组中

php - 将键值对添加到现有数组

c - `while(1)`如何优化不占用所有资源?

php - 通过PHP在MySQL中插入元素我得到语法错误

javascript - 数组到对象单行

javascript - 通过单击按钮创建一个 div

arrays - 在较大数组中查找小数组中的各个字符串

php - 遍历 POST 字段并设置为变量 PHP

c# - 用于 C# 应用程序的 PHP Web 服务

php - 如何获取 simplexml 对象的所有元素