2015-12-26 116 views
3

我有兩個數組PHP的:數組嵌套循環性能

$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秒..和太多

我能做些什麼來執行更第一種方法的情況呢?

回答

1

你可能有一些成功的兩次迭代,並使用共同的參數在分配

$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); 
+0

它運行得更快。謝謝! (〜0.280秒) – daniel

+0

好消息! – Scuzzy