簡體   English   中英

如何從數組中排序並獲取最小值和最大值?

[英]How to sort and get the min & max Value from an Array?

我有2個數組

//each array contains 8 values
$ids = Array(1441, 1313, 1123, 1316, 1313, 1313, 1123, 1567);
//each id has a value in $data array
$data = Array(2, 3, 8, 4, 5, 4, 2, 9);


//here is my problem: 

$max_data = array_product($data); //but not all values from $data only these:
$ids = [1441,1123,1316,1313,1567]; //these are the ids with highest data.
echo $max_data; //result must be 2880 (2 * 8 * 4 * 5 * 9)
$min_data = array_product($data); //and now
$ids = [1441,1313,1316,1123,1567]; //these are the ids with lowest data.
echo $max_data; //result must be 432 (2 * 3 * 4 * 2 * 9)

希望我能解釋我的問題。

謝謝。


解決了。

我做了一個獲取最大值和最小值的函數。 我想得到更好的答案,謝謝!

<?php

$ids = Array(1441, 1313, 1123, 1316, 1313, 1313, 1123, 1567);           
$data = Array(2, 3, 8, 4, 5, 4, 2, 9);

function getMaxData($ids, $data)
{
    (int)$_total = 1;
    array_multisort($ids, $data, SORT_DESC);

    foreach(array_unique($ids) as $key => $value)
        $_total *= $data[$key];

    return $_total;
}

function getMinData($ids, $data)
{
    (int)$_total = 1;
    array_multisort($ids, $data, SORT_ASC);

    foreach(array_unique($ids) as $key => $value)
        $_total *= $data[$key];

    return $_total;
}

echo "Max: ".getMaxData($ids, $data)."<br />";
echo "Min: ".getMinData($ids, $data)."<br />";

?>

我不確定我是否理解正確,但是您不需要關聯數組嗎?

$foo = Array(2 => 1441, 3 => 1313 .... )

http://php.net/manual/zh/language.types.array.php

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM