我想获取嵌套的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++;
}
}
答案 0 :(得分:2)
是否有可能最后一个元素没有完全填充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
的{{1}}的第一个和最后一个元素进行操作,则应事先传递一次数组以首先找出它们的确切索引。
$row['category']['cat_id'] == $s['Service']['category_id']