PHP-检查foreach的先前值是否等于当前值

时间:2018-07-29 20:59:05

标签: php html

我有以下数组:

Array (
    [0] => Array ( [from] => Person 1 [to] => Person 2 [content] => Hello )
    [1] => Array ( [from] => Person 1 [to] => Person 2 [content] => How are you? )
    [2] => Array ( [from] => Person 2 [to] => Person 1 [content] => Oh, hey there. I'm fine )
    [3] => Array ( [from] => Person 2 [to] => Person 1 [content] => What about you? )
)

我想遍历它,以便如果当前[from]等于先前的[from],那么将创建一个包含<p>作为内部HTML的[content]元素。如果不相等,则创建一个<div>并显示[content]

因此,输出应为:

<div>
    <p>Hello</p>
    <p>How are you?</p>
</div>
<div>
    <p>Oh, hey there. I'm fine</p>
    <p>What about you?</p>
</div>

1 个答案:

答案 0 :(得分:2)

使用for循环遍历它:

$count = count($array);
for ($i=0; $i<$count; $i++) {
    $item = $array[$i];
    $lastFrom = null;
    if ($i > 0) {
        $lastFrom = $array[$i-1]['from'];
    }

    if ($item['from'] !== $lastFrom) {
        // Item is different, do different things here
    }
}

或者,将$lastFrom存储在循环中:

$lastFrom = null;
foreach ($array as $item) {
    if ($item['from'] !== $lastFrom) {
        // Item is different, do different things here
    }

    $lastFrom = $item['from'];
}