如果出现foreach值,请添加一些数据

时间:2011-10-09 03:35:18

标签: php loops foreach

我得到了:

foreach ($query as $sample) {
[..]
}

如果所有值都是

,我需要更改它

$sample['key'] == 1

将被foreach循环,下一个循环将有$sample['key'] == 0,然后它会添加例如:

<tr><td colspan="4">All keys with $sample['key'] == 1 are after the loop, and I'm staring to loop with $sample['key'] == 0</td></tr>

但只有一次。

//编辑

尝试解释更多:

首先:foreach将循环显示:

foreach($query as $sample) {
*loop*
print_r($sample['key']) //1
*loop*
print_r($sample['key']) //1
...etc.
}

但如果有类似的东西:

foreach($query as $sample) {
*loop*
print_r($sample['key']) //1
*loop*
*adding some content, because next print value is 0!*
print_r($sample['key']) //0!!!!!!!
}

希望你现在明白,我尽我所能尽力解释。这很难描述,所以如果你有一些问题,请随时在评论中提问。

1 个答案:

答案 0 :(得分:1)

我不确定我是否100%理解这个问题,但听起来几乎像array_filter可能会有所帮助:

function KeyIsEqualToOne($ary){
  return $ary['key'] == 1;
}

function KeyIsEqualToZero($ary){
  return $ary['key'] == 0;
}


// all elements where key==1
$KeysWithOne = array_filter($query, 'KeyIsEqualToOne');

// all elements where key==0
$KeysWithZero = array_filter($query, 'KeyIsEqualToZero');

否则您可以随时保留状态变量以查看切换的时间:

$HasSeenZeroValue = false;
foreach ($query as $sample){
  // ...
  if ($sample['key'] == 0 && !$HasSeenZeroValue){
    echo '<tr><td>...</td></tr>';
    $HasSeenZeroValue = true;
  }
}

虽然,诚然,我并不是100%得到你所要求的。