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
循環?
如果您知道密鑰。那麼你可以直接訪問數據。 –
如果您不知道密鑰,那麼這將是訪問數據的最佳方式。也可以把它變成你需要重複使用它的功能。 'in_array'也可能會有幫助 – Austin
讓我看看你的原始代碼。所以基於這個我可以幫你 –