我想得到嵌套的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'])
?
尝试将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++;
}
}
?>