数组嵌套循环性能

数组嵌套循环性能

我有两个阵列

$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秒内完成。太多了
在第一种方法的情况下,我可以做什么来执行更多的操作?

最佳答案

通过两次迭代和在赋值中使用公共参数,您可能会取得一些成功

$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 - PHP:数组嵌套循环性能,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34471273/

10-09 19:24