如何从foreach循环的下一次迭代中获取值

时间:2017-08-06 19:17:53

标签: php

我正在尝试打印SQL数据库中的条目。一些条目是图像,我想解析它们并将它们放在适当的HTML标记中。

数据库示例

id | datatype  | typetext

78 | paragraph | "hello"
79 | image     | "image.jpg"
80 | paragraph | "goodbye"

datatype表示在给定行中存储的数据类型,我希望在datatype的值为“image”时捕获 - 然后跳转到以下{{1 }列并为此图像准备适当的标记。

例如,我正在尝试做的一些假代码:

typetext

这是我目前的代码:

if(column is datatype){
    if(datatype == 'image'){
        echo '<p>' . data inside accompanying typetext column . '</p>';
    }
}

在第一个//the array of the blog entry foreach($entry as $key => $entryUnit){ //the array of the entry unit foreach($entryUnit as $column => $cell){ if($column == 'datatype'){ if($key == 'image'){ echo '<br/>'; echo '<p style="color: pink;">' $cell . $entryUnit[$column + 1] . '</p>'; echo '<br/>'; } } else if($column == 'typetext'){ echo '<br/>'; echo $cell; echo '<br/>'; } } } 语句中,我尝试使用if跳转到下一列,但这不起作用。

我也尝试过使用echo '<p style="color: pink;">' $cell . $entryUnit[$column + 1] . '</p>';功能,例如:

next()

..但这也不像我想的那样有用。

2 个答案:

答案 0 :(得分:3)

您不需要那些嵌套的foreach循环,只需一个简单的foreach循环即可完成所有操作。

foreach($entry as $entryUnit){
    if($entryUnit['datatype'] == "image"){
        echo '<br/>';
        echo '<p style="color: pink;">' . $entryUnit['typetext'] . '</p>';
        echo '<br/>';
    }elseif($entryUnit['datatype'] == "paragraph"){
        echo '<br/>';
        echo $entryUnit['typetext'];
        echo '<br/>';
    }
}

答案 1 :(得分:2)

这样的想法应该有效:

 //the array of the blog entry
foreach($entry as $key => $entryUnit){
$i=0;
    //the array of the entry unit
    foreach($entryUnit as $column => $cell){

        if($column == 'datatype'){
            if($key == 'image'){
$i++;
                echo '<br/>';
                echo '<p style="color: pink;">' $cell . $entryUnit[$i] . '</p>';
                echo '<br/>';
            }
        }

        else if($column == 'typetext'){
            echo '<br/>';
            echo $cell;
            echo '<br/>';
        }
    }
}
相关问题