我想显示10个数据中最大的5个数组

时间:2019-04-24 03:50:40

标签: php arrays

我的代码是:

$dataBerita = array(
 'Babakan' => array(5),
 'Babakan Pasar' => array(30),
 'Bantar Jati' => array(70),
 'Baranang Siang' => array(50),
 'Batutulis' => array(40),
 'Bojongkerta' => array(25),
 'Bondongan' => array(90),
 'Ciampea' => array(5),
 'Cibadak' => array(2),
 'Cilubang' => array(6)
);

array_multisort($dataBerita, SORT_DESC);

foreach ($dataBerita as $key => $value) {
 echo $value.", ";
}

我要显示10个数据阵列中最大的5个数据阵列,如下所示:

90,70,50,40,30,

2 个答案:

答案 0 :(得分:0)

将您的foreach更改为

foreach (array_slice($dataBerita,0, 5) as $key => $value) {
    echo $dataBerita[$key][0].',';
}

答案 1 :(得分:0)

您需要通过删除除前5个之外的所有内容来对数组进行排序和拼接

$top = 5; // you can change it anytime
array_multisort($dataBerita, SORT_DESC);
array_splice($dataBerita, -(count($dataBerita)-$top));

array_splice-删除数组的一部分,并用其他东西替换

输出

Array
(
    [Bondongan] => Array
        (
            [0] => 90
        )

    [Bantar Jati] => Array
        (
            [0] => 70
        )

    [Baranang Siang] => Array
        (
            [0] => 50
        )

    [Batutulis] => Array
        (
            [0] => 40
        )

    [Babakan Pasar] => Array
        (
            [0] => 30
        )

)

Demo