Home > Backend Development > PHP Tutorial > PHP 获取数组指定部分

PHP 获取数组指定部分

WBOY
Release: 2016-06-06 20:42:59
Original
1505 people have browsed it

有数组
$arr=[ 1=>'aaa', 2=>'bbb', 3=>'ccc', 4=>'ddd' ]; $keys=[1,3];

问有没有现成的函数获取$arr中key为1,3的项, 组成一个新数组返回.
难道非得foreach么?

===============================
需求有点变动
要获取 $keys=[1,3,1,3];
就是说会有重复key. 麻烦~

3q

回复内容:

有数组
$arr=[ 1=>'aaa', 2=>'bbb', 3=>'ccc', 4=>'ddd' ]; $keys=[1,3];

问有没有现成的函数获取$arr中key为1,3的项, 组成一个新数组返回.
难道非得foreach么?

===============================
需求有点变动
要获取 $keys=[1,3,1,3];
就是说会有重复key. 麻烦~

3q

<code class="lang-php">$arr=[
    1=>'aaa',
    2=>'bbb',
    3=>'bbb',
    4=>'bbb'
];

$keys=[1,3];

$result = array_intersect_key($arr, array_fill_keys($keys, 0));

print_r($result);
</code>
Copy after login

1.

<code>$arr_tmp =  array($arr['1'],$arr['3']);
</code>
Copy after login

2.

<code>array_filter($arr,funtion($v,$k) use ($keys){
    return isset($keys[$k])?true:false;
});
</code>
Copy after login

代码未测试

Related labels:
php
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template