dongpa3109 2018-12-04 17:16
浏览 58
已采纳

按顺序在php数组中查找值

I am working with an array constructed from input from a form. I need to find if two values are in the array in sequence. If I use in_array it comes back true searching for one value or the other, but I need to find if they are in sequence as there is a chance two values are in the array. Example:

 [0] => location [1] => Riverside [2] => location [3] => Other [4] => subcat1 [5] => Motorcycle [6] => subcat2 [7] => Other.

If I use array_search or in_array, looking for 'Other' it returns true and stops on the first value found, but I need to know if the value subcat2 is immediately followed by 'Other' in the array. Using the values repopulates the form and since 'Other' is in the array twice (or more), it marks all the 'Other' options in the form. I want to capture the value pairs. Any ideas?

  • 写回答

2条回答 默认 最新

  • drv16759 2018-12-04 17:36
    关注

    You could create a function.

    function findpair($initial_array,$value1,$value2){
     $found=false;
     foreach($initial_array as $key=>$value){
      if(isset($initial_array[$key+1])){
       if($value1==$value and $initial_array[$key+1]==$value2){$found=true;}
      }
     }
     return $found;
    }
    findpair($array,'Other','subcat2');
    

    You can change $found to return the key of the first found value/pair if you want. This just returns TRUE or FALSE.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题