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

在一些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);
     }
}

真的好纠结,总是想着进阶,可是没有头绪,公司就我自己php,连交流的人都没有.....................心累

转载自[dodobook]

你可能感兴趣的:(php学习)