PHP的数组中如何根据某一个value值获取其key值

  •   
  • 6101
  • PHP
  • 7
  • super_dodo
  • 2016/09/12

在一些PHP的场景之中可能会遇到,在PHP的数组中需要根据其中某一个value值来获取得到其key的值。这个时候我们就需要使用到PHP数组函数中的array_search()这个方法。使用方法如下:

//array_search()的使用方法
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);   // $key = 1;


//array_key_exists()的使用方法
$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)) {
    echo "The 'first' element is in the array";
}


//相关函数有
array_keys() - Return all the keys or a subset of the keys of an array
array_values() - Return all the values of an array
array_key_exists() - Checks if the given key or index exists in the array
in_array() - Checks if a value exists in an array


//得到上次访问的用户的时间
$curKey = array_search($createTime,$date_arr);
$prevKey = $curKey + 1;
if(array_key_exists($prevKey,$date_arr)){
     $prevTime = intval($date_arr[$prevKey]);
     if($prevTime){
            $prevDate = Date('Y-m-d H:i:s',$prevTime/1000);
     }
}

张爱玲说:“我在街沿急急走着,每一脚踏在地上都是一个响亮的吻”