2017-05-11 54 views
1

使用PHP和MySQL我已經生成了兩個數組。我想遍歷這些數組,從兩個數據中檢索數據並一起顯示在一個句子中。PHP foreach循環和數據檢索

foreach ($items as $item) { 
    if(isset($item->item_title)) { 
     $itemTitle = $item->item_title; 
    } 
    // var_dump($itemTitle); 
    // string(7) "Halfway" string(5) "Story" string(6) "Listen" 
} 

foreach ($aData["Items"]["Item"] as $a) { 
    if (isset($a['description'])) { 
     $aDescription = $a['description']; 
    } 
    // var_dump($aDescription ); 
    // string(4) "Good" string(6) "Strong" string(2) "OK" 
} 

?> 

預期結果;

The title is Halfway and the description is Good. 
The title is Story and the description is Strong. 
The title is Listen and the description is OK. 
// etc 
// etc 

是否有可能巢foreach迴路,或者有更好的更有效的方法?

+0

請分享您的輸入數組。 –

+0

不幸的是,我沒有這些數據。如果有某些方法或功能,你可以推薦我願意親自看看他們。我只需要在正確的方向輕推!邏輯拋棄了我:/ –

+0

我希望我的文章能像你所期望的一樣幫助你。 –

回答

0

請試試這個方法。希望這個幫助!

foreach ($items as $index => $item) { 
    if(isset($item->item_title)) { 
     $itemTitle = $item->item_title; 
     echo 'The title is '.$itemTitle; 
    } 
    if(isset($aData["Items"]["Item"][$index]['description']) { 
     $itemDescription = $aData["Items"]["Item"][$index]['description']; 
     echo ' and the description is '.$itemDescription; 
    } 
    echo '<br>'; 
    // The title is Halfway and the description is Good. 
} 
0

試試這個希望這會幫助你。

注意:這裏我假設兩個數組都有相同的索引。

$items
$aData["Items"]["Item"]

如果沒有,你可以做array_values($items)array_values($aData["Items"]["Item"])

foreach ($items as $key => $item) 
{ 
    if (isset($item->item_title) && isset($aData["Items"]["Item"][$key]['description'])) 
    { 
     $itemTitle = $item->item_title; 
     echo sprinf("The title is %s and the description is %s",$itemTitle,$aData["Items"]["Item"][$key]['description']); 
     echo PHP_EOL; 
    } 
} 
0

您可以使用一個簡單的for循環合併這兩個foreach循環,就像這樣:

$count = count($items) >= count($aData["Items"]["Item"]) ? count($aData["Items"]["Item"]) : count($items); 

for($i = 0; $i < $count; ++$i){ 
    if(isset($item[$i]->item_title)) { 
     $itemTitle = $item[$i]->item_title; 
    } 
    if (isset($aData["Items"]["Item"][$i]['description'])) { 
     $aDescription = $aData["Items"]["Item"][$i]['description']; 
    } 
    // your code 
} 

旁註:上面的代碼假設兩個數組$items$aData["Items"]["Item"]具有不同數量的元素,但這也適用於相同數量的元素。如果您確信這兩個數組將始終具有的元素數量相等,然後重構$count = ... ;聲明以下列方式,

$count = count($items); 

$count = count($aData["Items"]["Item"]); 

for循環使用$count變量。