2017-05-09 104 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