首页 > 解决方案 > 如何在 php 中找到嵌套 foreach 循环的迭代

问题描述

我想获取嵌套 foreach 循环的第一个元素和结束元素,条件对于第一个循环工作正常,但它不适用于第二个嵌套循环。

PHP 代码

$i = 0;
$len = count($category_tbl_data);
foreach($category_tbl_data as $row) {?>
   if ($i == 0) {
       // first element working fine
   }
   if ($i == $len - 1)
   {
      // last element working fine
   }

   $j=0;
   $len2 = count($services);
   foreach($services as $s){
    if($row['category']['cat_id'] == $s['Service']['category_id'])
    {
      if ($j == 0) {
       // first element working fine
    }
    if ($j == $len2 - 1)
    {
      // last element not working
    }

    }
   $j++;
  }
}

图片在这里

标签: php

解决方案


已回答

最后一个元素是否有可能没有完全填充if($row['category']['cat_id'] == $s['Service']['category_id'])

如果您想对 的确切第一个和最后一个元素进行操作,请尝试放置if ($j == 0) {}if ($j == $len2 - 1){}外部,无论是什么。if($row['category']['cat_id'] == $s['Service']['category_id']){}$services$s

<?php

$len = count($category_tbl_data);
foreach($category_tbl_data as $i => $row) {
    if ($i == 0) 
    {
        // first element working fine
    }
    if ($i == $len - 1)
    {
        // last element working fine
    }

    $len2 = count($services);
    foreach($services as $j => $s){
        if ($j == 0) 
        {
            // first element 
        }
        if($row['category']['cat_id'] == $s['Service']['category_id'])
        {

        }
        if ($j == $len2 - 1)
        {
            // last element 
        }
        $j++;
    }
}
?>

如果要对$services满足的第一个和最后一个元素进行操作$row['category']['cat_id'] == $s['Service']['category_id'],则应事先将数组传递一次,以首先找出它们的确切索引。

<?php
$len = count($category_tbl_data);
foreach($category_tbl_data as $i => $row) {
    if ($i == 0) 
    {
        // first element working fine
    }
    if ($i == $len - 1)
    {
        // last element working fine
    }

    $len2 = count($services);
    $first = -1;
    $last = -1;
    foreach($services as $j => $s)
    {
        if($row['category']['cat_id'] == $s['Service']['category_id'])
        {
            if($first < 0)
            {
                $first = $j;
            }
            $last = $j;
        }
    }
    foreach($services as $j => $s){

        if($row['category']['cat_id'] == $s['Service']['category_id'])
        {
            if ($j == $first) 
            {
                // first element
            }
            if ($j == $last)
            {
                // last element 
            }
        }

    }
}
?>

推荐阅读