如何获取多维数组中第二高的元素值。
我用这个函数得到最高的值。但我怎么能找到第二高的。
function get_max($array)
{
$max = -999999999;
$found_item = null;
foreach ($array as $key => $value) {
if ($value['transaction_no'] > $max) {
$max = $value['transaction_no'];
$found_item = $value;
}
}
return $found_item;
}
例如,如果我调用
get_max($transactions)
得到数组4,因为它在事务中有最高的值:5,但如何才能得到第二高的值?例如,当我调用get_second_max($transactions)
时,我应该得到数组3,因为它在事务编号中有4。$transactions = Array
(
[0] => Array
(
[transaction_user_id] => 359691e27b23f8ef3f8e1c50315cd506
[transaction_no] => 1
[transaction_total_amount] => 589.00
[transaction_date] => 1335932419
[transaction_status] => cancelled
)
[1] => Array
(
[transaction_user_id] => 9def02e6337b888d6dbe5617a172c18d
[transaction_no] => 2
[transaction_total_amount] => 79.00
[transaction_date] => 1336476696
[transaction_status] => cancelled
)
[2] => Array
(
[transaction_user_id] => 9def02e6337b888d6dbe5617a172c18d
[transaction_no] => 3
[transaction_total_amount] => 299.00
[transaction_date] => 1336476739
[transaction_status] => cancelled
)
[3] => Array
(
[transaction_user_id] => 9def02e6337b888d6dbe5617a172c18d
[transaction_no] => 4
[transaction_total_amount] => 79.00
[transaction_date] => 1336476927
[transaction_status] => cancelled
)
[4] => Array
(
[transaction_user_id] => 8e9050a3646c98342b9ba079fba80982
[transaction_no] => 5
[transaction_total_amount] => 129.00
[transaction_date] => 1336477032
[transaction_status] => cancelled
)
)
最佳答案
<?php
function get_max($array) {
$all = array();
foreach($array as $key=>$value){
$all[] = $value['transaction_no'];
}
rsort($all);
return $all[1];
}
要返回数组而不仅仅是值,请执行以下操作:
function get_max($array) {
$all = array();
foreach($array as $key=>$value){
/* creating array where the key is transaction_no and
the value is the array containing this transaction_no */
$all[$value['transaction_no']] = $value;
}
/* now sort the array by the key (transaction_no) */
krsort($all);
/* get the second array and return it (see the link below) */
return array_slice($all, 1, 1)[0];
}
PHP: Get n-th item of an associative array