避免PHP foreach的双重结果

时间:2014-04-30 06:13:57

标签: php foreach

如何从下面的代码中避免双重“我最喜欢的颜色”? 我需要的是跳过双重我最喜欢的颜色。谢谢你......

<?php

$color = array(
            "blue"=> array("status"=>"my favorite colors"),
            "green"=> array("status"=>"my favorite colors"),
            "red"=> array("status"=>"NOT my favorite colors")
                );

    foreach ( $color as $myfav ) {

        echo $myfav['status']."<br>";

        }

?>

4 个答案:

答案 0 :(得分:2)

您可以将此视为一个示例:

$color = array(
    "blue"=> array("status"=>"my favorite colors"),
    "green"=> array("status"=>"my favorite colors"),
    "red"=> array("status"=>"NOT my favorite colors")
);

$favorite = array();
foreach($color as $key => $myfav) {
    if(!in_array($myfav['status'], $favorite)) {
        $favorite[$key] = $myfav['status'];
    }
}


print_r($favorite);

输出:

Array
(
    [blue] => my favorite colors
    [red] => NOT my favorite colors
)

首先将它们放在数组中,然后检查是否已存在,然后它将跳过。

编辑:如果你想获得钥匙(你想保留它们,因为你们都喜欢蓝色和绿色),你可以使用它:

foreach($color as $key => $myfav) {
    $exists = array_search($myfav['status'], $favorite);
    if($exists === false) {
        $favorite[$key] = $myfav['status'];
    } else {
        unset($favorite[$exists]);
        $exists .= ', ' . $key;
        $favorite[$exists] = $myfav['status'];
    }
}

输出:

Array
(
    [blue, green] => my favorite colors
    [red] => NOT my favorite colors
)

答案 1 :(得分:0)

use continue;这将在循环中结束当前迭代,确保将它放在您不需要执行该迭代的任何代码之前

<?php

$color = array(
            "blue"=> array("status"=>"my favorite colors"),
            "green"=> array("status"=>"my favorite colors"),
            "red"=> array("status"=>"NOT my favorite colors")
                );

    foreach ( $color as $myfav ) {

        if($myfav['status'] == 'my favorite colors') continue;

        echo $myfav['status']."<br>";

        }

?>

编辑/更多信息:如果你想在第一次得到条件时运行迭代,你可以在每次出现条件时递增一个整数,然后使用continue;当它达到2或其他数字时

答案 2 :(得分:0)

这会对你有帮助,

<?php

$color = array(
            "blue"=> array("status"=>"my favorite colors"),
            "green"=> array("status"=>"my favorite colors"),
            "red"=> array("status"=>"NOT my favorite colors")
                );

    foreach ( $color as $myfav ) {
        $lastStatus = '';
        if ($myfav['status'] != $lastStatus) {
            echo $myfav['status']."<br>";
        }
        $lastStatus = $myfav['status'];

        }

?>

如果您需要任何其他帮助,请告诉我。

答案 3 :(得分:0)

$arr = array();

foreach ($color as $key => $myfav) $arr[$key] = $myfav['status']; //strtolower()?

foreach (array_unique($arr) as $key => $myfav)
{
    //$color[$key]
}

unset($arr);

使用带有键的临时变量和来自$ color的'status'文本来应用array_unique函数。最后,我们使用$ color中的原始键迭代唯一数组。