Home > Backend Development > PHP Tutorial > 今天写PHP的时候遇到了一个关于数组的问题

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

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-06 20:30:11
Original
947 people have browsed it

<code>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 
);
</code>
Copy after login
Copy after login

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

回复内容:

<code>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 
);
</code>
Copy after login
Copy after login

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

<code><?php $array = 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 
);
//通过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开始
</code>
Copy after login
Related labels:
php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template