dongxie9448 2011-10-09 03:35
浏览 4
已采纳

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

I got:

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

And I need it to be changed so if all values with

$sample['key'] == 1

Gonna be looped by the foreach and the next loop will have $sample['key'] == 0 , then it'll add for example something like:

<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>

But only once.

//edited

Trying to explain more:

At first: foreach will loop this:

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

But if there'll be something like:

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!!!!!!!
}

Hope you understand it now, I've done my best to explain as best as I can. It's hard to describe, so if you have some questions, feel free to ask in the comments.

  • 写回答

1条回答 默认 最新

  • doujiao1905 2011-10-09 04:03
    关注

    I'm not sure I 100% understand the question, but it sounds almost like array_filter may be of some help:

    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');
    

    Otherwise you could always keep a state variable to see when the switch was made:

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

    Though, admittedly, I don't 100% get what you're asking.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 我的数据无法存进链表里
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端