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 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b