我在$data
内有一个[23:45]
数组,其数组包含userid
和login
时间:
$data = array(
[93] => array(
[23:34] => array(
[0] => array(
[userid]=> 93,
[login] =>23:34:03
),
[1] => array(
[userid]=> 93,
[login] =>23:34:07
),
[2] => array(
[userid]=> 93,
[login] =>23:34:02
)
)
)
)
我想要的输出是:
$data = array(
[93] => array(
[23:45] => array(
[0] => array(
[userid]=> 93,
[login] =>23:34:02
)
)
)
)
唯一的左边是最早登录,另一个阵列应该删除。请帮忙
答案 0 :(得分:1)
找到最短时间:
$earliest = 0;
for ($i = 1; $i < count($data[93]["23:45"]; $i++){
if (strcmp($data[93]["23:45"][$i]["login"], $data[93]["23:45"][$earliest]["login"]) < 0){
$earliest = $i;
}
}
然后用新的数组替换数组,只包含最早的登录名:
$data[93]["23:45"] = array(
$data[93]["23:45"][$earliest]
);
答案 1 :(得分:1)
首先对数组进行排序,然后排序unset
除数组中0索引处的第一项以外的所有项目。
<?php
$data = array(
'93' => array(
'23:34' => array(
0 => array(
'userid'=> 93,
'login' =>'23:34:03'
),
1 => array(
'userid'=> 93,
'login' =>'23:34:07'
),
2 => array(
'userid'=> 93,
'login' =>'23:34:02'
)
)
)
);
usort($data['93']['23:34'], build_sorter('login'));///sort array
function build_sorter($key) ///custom sort function just pass the key
{
return function ($a, $b) use ($key) {
return strnatcmp($a[$key], $b[$key]);
};
}
foreach($data['93']['23:34'] as $key => $val)
{
if($key != 0)
{
unset($data['93']['23:34'][$key]); ///remove all the items except first item..
}
}
print_r($data);
?>
这会给你:
Array
(
[93] => Array
(
[23:34] => Array
(
[0] => Array
(
[userid] => 93
[login] => 23:34:02
)
)
)
)