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

PHP 获取数组指定部分

WBOY
WBOYOriginal
2016-06-06 20:42:591502browse

有数组
$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>

1.

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

2.

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

代码未测试

Statement:
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