打破foreach()循环并将剩余的条目存储在新数组中

时间:2014-11-16 18:48:17

标签: php arrays foreach

我有一个foreach循环,用于比较数组中前一个和当前记录的类别字段,并检查它们是否匹配。如果两个字段不匹配,则循环被破坏。

    $rows = array();

    while ( $row = mysqli_fetch_array($result)){            
            $rows[] = $row;
    }


    $previous = 'FROG';

    echo"<div class='rowtable'>";

    foreach($rows as $row)
    {
        $commondraft = $row['Name'];
        $current = $row['Category'];

        if($current==$previous){

        echo"<a href='/stocklist/".$row['id']."/".commonName($commondraft)."' class='row'>";
        echo"<div class='common'>".$row['Name']."</div>"; 
        echo"<div class='descr'>".$row['Description']."</div>";
        echo"<div class='sex'>".$row['Sex']."</div>"; 
        echo"<div class='age'>".$row['Age']."</div>"; 
        echo"<div class='size'>".$row['Size']."</div>";  
        echo"<div class='origin'>".$row['Origin']."</div>"; 
        echo"<div class='scientific'>".$row['Scientific']."</div>"; 
        echo"<div class='prices'>".$row['Price']."</div>"; 

        echo"</a>";
        }

        $previous=$current;
        }

我需要找到一种方法将数组中的剩余记录存储到一个新数组中,以便它们可以在第二个foreach循环中的其他地方使用。

解: 跟随@LukasS,建议。我想我现在使用下面的代码发布给其他感兴趣的人:

$query =    "SELECT * FROM livestock    WHERE Category = 'frog' OR Category = 'newt'";
    $result = mysqli_query($con, $query) or die(mysqli_error($con));  
    $rows = array();

    while ( $row = mysqli_fetch_array($result)){            
            $rows[$row['Category']][] = $row;}



    $previous = 'FROG';

    echo"<div class='rowtable'>";

    foreach($rows['FROG'] as $row)
    {
        $commondraft = $row['Name'];
        $current = $row['Category'];

        if($current==$previous){

        echo"<a href='/stocklist/".$row['id']."/".commonName($commondraft)."' class='row'>";
        echo"<div class='common'>".$row['Name']."</div>"; 
        echo"<div class='descr'>".$row['Description']."</div>";
        echo"<div class='sex'>".$row['Sex']."</div>"; 
        echo"<div class='age'>".$row['Age']."</div>"; 
        echo"<div class='size'>".$row['Size']."</div>";  
        echo"<div class='origin'>".$row['Origin']."</div>"; 
        echo"<div class='scientific'>".$row['Scientific']."</div>"; 
        echo"<div class='prices'>".$row['Price']."</div>"; 

        echo"</a>";
        }

        $previous=$current;
        }



    echo"</div>";

2 个答案:

答案 0 :(得分:1)

在我看来,如果有办法保持密钥清洁,你应该使用关联数组。

例如,相反$rows[]Category键与$rows[$row['Category']][] = $row;分开,并在该关联数组中使用每个键。{/ p>

答案 1 :(得分:0)

你可以使if取决于比较和布尔值。然后,如果它未命中,则在else上切换布尔值并使用它将其余部分转储到新数组

$bool = TRUE;
$newArray = array();
foreach($rows as $row){
    if($current==$previous && $bool === TRUE){
        /*Things happening*/
    }else{
        $bool = FALSE;
        $newArray[] = $row;
    }
}