PHP foreach循环和数据检索

时间:2017-05-11 16:07:56

标签: php arrays loops oop foreach

使用PHP和MySQL我生成了两个数组。我想遍历这些数组,从两者中检索数据并在一个句子中一起显示。

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循环,还是有更好的方法?

3 个答案:

答案 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. 
}

答案 1 :(得分: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;
    }
}

答案 2 :(得分:0)

您可以使用简单的foreach循环合并这两个for循环,如下所示:

$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"]);

并在$count循环中使用此for变量。