PHP:嵌套 foreach 循環的問題 (PHP: Issue with nested foreach loops)


問題描述

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:

  1. $test is not initialized.
  2. The if($category_title) only checks for the values existence. Not for it to be iterable. You might want to use is_array().
  3. 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;
  4. 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 FellUmesh ChauhanMetterschling)

參考文件

  1. PHP: Issue with nested foreach loops (CC BY‑SA 2.5/3.0/4.0)

#php-5.5 #PHP #xpath






相關問題

當作為參數傳遞時,PHP 如何解釋和評估函數和匿名函數? (How does PHP interpret and evaluate function and anonymous function when passed as an argument?)

使用 symfony 時 PHP 5.5 無法識別服務器 (PHP 5.5 won't recognise server when using symfony)

升級到 PHP5.5 時 Wordpress 崩潰 (Wordpress crashes when upgrading to PHP5.5)

從數據庫返回多個值 (return multiple values from database)

PHP:嵌套 foreach 循環的問題 (PHP: Issue with nested foreach loops)

如果條件在幾小時、幾天內不起作用 (if condition not working for Hours,Days)

Slim 3.3 輸出中缺少字符 (Slim 3.3 missing characters in output)

PHP排序對象值但保留原始相對順序 (PHP sort objects value but retain original relative order)

遇到錯誤無法加載請求的文件:helpers/form_validation_helper.php (An Error Was Encountered Unable to load the requested file: helpers/form_validation_helper.php)

如何從類的函數內部訪問全局變量 (How to access global variable from inside class's function)

如何修改輸出緩衝區? (How to modify output buffer?)

在同一台 Ubuntu 服務器上安裝和配置 PHP5 和 7 (Install and configure PHP5 and 7 on same Ubuntu server)







留言討論