函数说明
array_keys():返回数组中所有的键名。
array_search():在数组中搜索给定的值,如果成功则返回相应的键名。
//根据一个key返回关联数组中的另一个key,并且不使用foreach
// function array_key_relative(array $array, string $current_key, int $offset)
function array_key_relative($array, $current_key, $offset = 1) {
// create key map
$keys = array_keys($array);
// find current key
$current_key_index = array_search($current_key, $keys);
// return desired offset, if in array, or false if not
if(isset($keys[$current_key_index + $offset])) {
return $keys[$current_key_index + $offset];
}
return false;
}
//Usage example:
$test_array = array(
"apple" => "Red, shiny fruit",
"orange" => "Orange, dull, juicy fruit",
"pear" => "Usually green and odd-shaped fruit",
"banana" => "Long yellow fruit that monkeys like to eat",
"cantelope" => "Larger than a grapefruit",
"grapefruit" => "Kind of sour"
);
echo array_key_relative($test_array, "apple", 2); // outputs "pear"
echo array_key_relative($test_array, "orange", -1); // outputs "apple" */
$next_key = array_key_relative($test_array, "banana", 1); // Get the key after banana (cantelope)
echo $test_array[$next_key]; // outputs "Larger than a grapefruit"
?>