php - 如何在 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++;
}
}
解决方案
已回答
最后一个元素是否有可能没有完全填充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
}
}
}
}
?>
推荐阅读
- google-drive-api - 我需要共享驱动器 API 详细信息才能访问驱动器使用百分比
- angular - 如何在 Angular 8 上有条件地加载两个子组件
- c# - 旋转对象捕捉到一个不以恒定速度移动的点
- python - 两个字节数组的交集
- installation - 是否可以为自制软件做一个预发布的公式?
- r - 一个嵌套的“for”循环,返回每月的每一天
- javascript - useState Hook 不会传递给其他函数
- html - 如何将物品卡排成一行 3
- pyspark - 使用 Synapse Analytics 将数据帧写入 SQL 专用数据库
- javascript - 如何使用 htlm、js 和 nodejs 在另一个页面中显示画布活动?