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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?