当前位置:Gxlcms > PHP教程 > 今天写PHP的时候遇到了一个关于数组的问题

今天写PHP的时候遇到了一个关于数组的问题

时间:2021-07-01 10:21:17 帮助过:18人阅读

array (
        22 => 3000,
        1 => 2900,
        8 => 2588,
        11 => 2400,
        6 => 2000,
        30 => 1900,
        39 => 1800,
        25 => 1400,
        40 => 1300,
        100 => 1244,
        15 => 1000,
        69 => 900,
        70 => 888,
        3 => 666,
        333 => 10 
);

PHP里面,这样的一个数组,怎样才能高效的取出前10个,怎样才能算出key为333的是第几个.

回复内容:

array (
        22 => 3000,
        1 => 2900,
        8 => 2588,
        11 => 2400,
        6 => 2000,
        30 => 1900,
        39 => 1800,
        25 => 1400,
        40 => 1300,
        100 => 1244,
        15 => 1000,
        69 => 900,
        70 => 888,
        3 => 666,
        333 => 10 
);

PHP里面,这样的一个数组,怎样才能高效的取出前10个,怎样才能算出key为333的是第几个.

 3000,
    1 => 2900,
    8 => 2588,
    11 => 2400,
    6 => 2000,
    30 => 1900,
    39 => 1800,
    25 => 1400,
    40 => 1300,
    100 => 1244,
    15 => 1000,
    69 => 900,
    70 => 888,
    3 => 666,
    333 => 10 
);
//通过array_slice截取前面10个元素
$arr1 = array_slice($array, 0, 10, true);
print_r($arr1);
//通过array_search来获取key为333的位置
$pos = array_search(333, array_keys($array));
echo $pos+1;//$pos+1为实际位置,$pos为数组中位置,0开始

人气教程排行