2017-05-09 103 views
0

为了访问一些嵌套值(对于DB插入),我需要对大型数据集执行“深度循环”。访问没有太多foreach循环的嵌套数据

目前我有以下代码,它工作,但它是非常缓慢,并最终在所有数据完成处理之前超时。我无法弄清楚如何在没有这么多循环的情况下获得嵌套数据。

样本数组:

$resultArray = [ 
    { 
    "item1": "value", 
    "item2": "value", 
    "item3": "value", 
    "item4": "value", 
    "item5": [ 
     { 
     "anothervalue1": "value", 
     "anothervalue2": "value", 
     "anothervalue3": "value", 
     "anothervalue4": "value", 
     "anothervalue5": "value"   
     }, 
     { 
     "anothervalue1": "value", 
     "anothervalue2": "value", 
     "anothervalue3": "value", 
     "anothervalue4": "value", 
     "anothervalue5": "value" 
     }, 
     { 
     "anothervalue1": "value", 
     "anothervalue2": "value", 
     "anothervalue3": "value", 
     "anothervalue4": "value", 
     "anothervalue5": "value" 
     } 
     { 
     // another 150+ 
     } 
    ] 
    } 
]; 

实施现状:

// Loop over main array 
foreach ($resultArray as $object) { 
    // Loop over each object 
    foreach ($object as $key => $value) { 
    if ($key === 'item5') { 
     // Loop over each 'item5' object 
     foreach ($value as $history_key => $history_value) { 
     foreach ($history_value as $history_deep_key => $history_deep_value) { 
      $arr = array( 
       $_GET['someparam'], // column1 data 
       $object['item1'], // column2 data 
       $_GET['anotherparam'], // column3 data 
       $object['item2'], // column4 data 
       $history_value['anothervalue1'], // column5 data 
       $history_value['anothervalue2'], // column6 data 
       $history_value['anothervalue3'], // column7 data 
       $history_value['anothervalue4'], // column8 data 
       $history_value['anothervalue5'], // column9 data 
       $object['item3'] // column10 data 
      ); 
      $statement = $link->prepare("INSERT INTO reporting_clients(column1, column2, column3, column4, column5, column6, column7, column8, column9, column10) 
       VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); 
      $statement->execute($arr); 
     } 
     } 
    } 
    } 
} 

是否有可能访问嵌套数据wihtout这么多foreach循环?

+1

如果您知道密钥。那么你可以直接访问数据。 –

+1

如果您不知道密钥,那么这将是访问数据的最佳方式。也可以把它变成你需要重复使用它的功能。 'in_array'也可能会有帮助 – Austin

+0

让我看看你的原始代码。所以基于这个我可以帮你 –

回答

1

是的,如果你知道访问什么值,并且你知道对象数组的键和结构或者任何数组,它是可能的。

你的情况。 e-g

$value = $resultArray[0]->item5[0]->anothervalue5; 
echo $value; 

如果它是多维数组而不是对象数组,只是用数组框改变箭头。

$value = $resultArray[0]['item5'][0]['anothervalue5']; 
echo $value; 
+1

非常感谢! – wper