dqoqnmb163241 2015-05-11 16:32
浏览 171
已采纳

如何跳过foreach里面的foreach迭代

I have an array of values, and i want to insert the values to another array but with an if condition, if the "if" is true I want to skip the iteration.

Code:

$array=array(array(1=>11,2=>22,3=>23,4=>44,5=>55));
$insert=array();
foreach($array as $k1=>$v1)
{
foreach($v1 as $k2=>$v2)
{
    if($v2==23)
    {
        break; 
    }
}
    $insert[]=$v1;
}

final result should look like that

Array
(
[0] => Array
    (
        [1] => 11
        [2] => 22
        [3] => 44
        [4] => 55
    )
)   

I tried using: break,return,continue...

Thanks

  • 写回答

3条回答 默认 最新

  • dsdukbc60905239 2015-05-11 16:51
    关注

    There are a few ways to do this. You can loop over the outer array and use array_filter on the inner array to remove where the value is 23 like this (IMO preferred; this also uses an array of $dontWant numbers so it is easier to add or change numbers later):

    <?php
    $array = array(array(1=>11,2=>22,3=>23,4=>44,5=>55));
    $insert = array();
    
    //array of numbers you don't want
    $dontWant = array(23);
    
    //loop over outer array    
    foreach($array as $subArray){
        //add to $insert a filtered array
        //subArray is filtered to remove where value is in $dontWant
        $insert[] = array_filter($subArray, function($val) uses ($dontWant) {
            //returns true if the value is not in the array of numbers we dont want
            return !in_array($val, $dontWant);
        });
    }
    //display final array    
    echo '<pre>'.print_r($insert,1).'</pre>';
    

    Or you can reference the first key to add to a sub array in $insert like (which is a little more like what your code is trying to do and show that you are not too far off):

    <?php
    $array = array(array(1=>11,2=>22,3=>23,4=>44,5=>55));
    $insert = array();
    //loop over outer array    
    foreach($array as $k1=>$v1){
        //add an empty array to $insert
        $insert[$k1] = array();
    
        //loop over inner array
        foreach($v1 as $k2=>$v2){
            //if the inner array value is not 23
            if($v2 != 23){
                //add to inner array in insert
                $insert[$k1][] = $v2;
            }
        }
    }
    //display the result    
    echo '<pre>'.print_r($insert,1).'</pre>';
    

    Both of these methods would produce the same result. IMO using array_filter is the preferred method, but the second method might be a little easier to understand for someone new to programming.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大