dongpa3109 2018-12-04 09: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 09: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条)
编辑
预览

报告相同问题?