問題描述
PHP:嵌套 foreach 循環的問題 (PHP: Issue with nested foreach loops)
基本上,我正在嘗試從多個 xPath 查詢中提取數據,並將從每個文件中提取的數據提交到 CSV 中的一行。我遇到的問題是遍歷特定的 xPath 查詢並將其結果連接到一行。
我有以下代碼:
$category_titles = $xpath‑>query('//*[@id="shopMain"]/div/div/h1');
$category_introduction = $xpath‑>query('//*[@id="shopMain"]/div/div/p');
if($category_title){
foreach($category_title){
foreach($category_introduction as $node){
$test .= $node‑>nodeValue;
var_dump($test);
continue();
}
$test = '':
}
}
我正在嘗試為每個 $category_title
循環 $category_introduction
查詢和連接每個
元素。然後,當所有
標記都已連接時,我嘗試跳出循環,並僅在清除 $test
的情況下重複該過程。誰能建議我如何在嵌套的 foreach 循環中做到這一點?我'
參考解法
方法 1:
i think the issue is with if condition and foreach loop because in if condition and foreach loop you have declared wrong variable
Try this
if($category_titles)
and
foreach($category_titles)
Instead of
if($category_title)
and
foreach($category_title)
方法 2:
In addition to Umesh Chauhans answer.
I see several problems with your code:
- $test is not initialized.
- The if($category_title) only checks for the values existence. Not for it to be iterable. You might want to use is_array().
- Your first foreach loop does not use the item to be iterated (the as $value part is missing). See PHP doc: foreach (array_expression as $value) statement;
- continue is a keyword not a function, so omit the (), look up the PHP doc as well
In general you might want to query $xpath‑>query('//*[@id="shopMain"]/div/div'); and then do subqueries.
(by Liam Fell、Umesh Chauhan、Metterschling)