问题
Is there an equivalent min()
for the keys in an array?
Given the array:
$arr = array(300 => 'foo', 200 => 'bar');
How can I return the minimum key (200
)?
Here's one approach, but I have to imagine there's an easier way.
function minKey($arr) {
$minKey = key($arr);
foreach ($arr as $k => $v) {
if ($k < $minKey) $minKey = $k;
}
return $minKey;
}
$arr = array(300 => 'foo', 200 => 'bar');
echo minKey($arr); // 200
回答1:
Try this:
echo min(array_keys($arr));
回答2:
Try with
echo min(array_keys($arr));
min()
is a php function that will return the lowest value of a set. array_keys()
is a function that will return all keys of an array. Combine them to obtain what you want.
If you want to learn more about this two functions, please take a look to min() php guide and array_keys() php guide
回答3:
use array_search()
php function.
array_search(min($arr), $arr);
above code will print 200
when you echo
it.
For echoing the value of lowest key use below code,
echo $arr[array_search(min($arr), $arr)];
Live Demo
回答4:
This also would be helpful for others,
<?php
//$arr = array(300 => 'foo', 200 => 'bar');
$arr = array("0"=>array('price'=>100),"1"=>array('price'=>50));
//here price = column name
echo minOfKey($arr, 'price');
function minOfKey($array, $key) {
if (!is_array($array) || count($array) == 0) return false;
$min = $array[0][$key];
foreach($array as $a) {
if($a[$key] < $min) {
$min = $a[$key];
}
}
return $min;
}
?>
回答5:
$arr = array(
300 => 'foo', 200 => 'bar'
);
$arr2=array_search($arr , min($arr ));
echo $arr2;
来源:https://stackoverflow.com/questions/18735462/how-can-i-return-the-minimum-key-in-an-array