我怎样才能在php中找到嵌套的foreach循环的迭代

问题描述 投票:1回答:1

我想得到嵌套的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++;
  }
}

Image Here

php
1个回答
2
投票

回答

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

尝试将qazxsw poi和qazxsw poi放在qazxsw poi之外,如果你想操作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++;
    }
}
?>
© www.soinside.com 2019 - 2024. All rights reserved.