对不起,我不太确定如何用言语表达我想要的东西。基本上我想得到一个密钥代码为0001的最小日期,我将如何实现呢?
$a=array(
"a" => array('keycode' => '0001','date' =>"2015-09-08"),
"b" => array('keycode' => '0002','date' =>"2015-09-05"),
"c" => array('keycode' => '0003','date' =>"2015-09-04"),
"d" => array('keycode' => '0001','date' =>"2015-09-01")
"e" => array('keycode' => '0001','date' =>"2015-08-01")
);
预期:$ result =" 2015-08-01"
答案 0 :(得分:1)
这将有效:
function min_date($a){
$dates = [];
foreach($a as $key => $value){
if($value['keycode']=='0001'){
array_push($dates,strtotime($value['date']));
}
}
return date("Y/m/d",min($dates));
}
$result = min_date($a);
答案 1 :(得分:1)
我首先会提取所有键码为0001的值,并创建一个仅包含这些日期的新数组。然后使用php min()
函数。
$a=array(
"a" => array('keycode' => '0001','date' =>"2015-09-08"),
"b" => array('keycode' => '0002','date' =>"2015-09-05"),
"c" => array('keycode' => '0003','date' =>"2015-09-04"),
"d" => array('keycode' => '0001','date' =>"2015-09-01"),
"e" => array('keycode' => '0001','date' =>"2015-08-01")
);
$b = [];
foreach($a as $key => $value){
if($value['keycode']=='0001'){
$b[]=$value['date'];
}
}
print_r($b);
echo min($b);
答案 2 :(得分:1)
这样就可以了 -
$a=array(
"a" => array('keycode' => '0001','date' =>"2015-09-08"),
"b" => array('keycode' => '0002','date' =>"2015-09-05"),
"c" => array('keycode' => '0003','date' =>"2015-09-04"),
"d" => array('keycode' => '0001','date' =>"2015-09-01"),
"e" => array('keycode' => '0001','date' =>"2015-08-01")
);
// Sort the array according to date in ascending order
usort($a, function($m, $n) {
return strtotime($m['date']) - strtotime($n['date']);
});
// Take out the first element
$first= array_shift($a);
echo $first['date'];
答案 3 :(得分:1)
您可以结合使用array_filter和uasort:
来执行此操作function getMinDateByKeycode(array $a, $keycode)
{
// Filter out elements by keycode
$aFiltered = array_filter($a, function($aItem) use ($keycode) {
return $aItem['keycode'] === $keycode;
});
// Sort lowest date first
uasort($aFiltered, function($a1, $a2){
return strtotime($a1['date']) - strtotime($a2['date']);
});
// Get the key of the first element of the resulting array
reset($aFiltered);
$keyOfMinDate = key($aFiltered);
// Return it however you want. This example returns just the date.
return $a[$keyOfMinDate]['date'];
}
echo getMinDateByKeycode($a, '0001');
// prints '2015-08-01'
答案 4 :(得分:1)
如果数组已经排序并且你使用的是PHP 5.5.0+,那么你可以试试这个
$arr = array_column($a, "date", "keycode");
echo $arr["0001"] // string(10) "2015-08-01"