array_map多个array进行map的时候,丢失了key?

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

Hi ,all

<code>$myarr=["22"=>1,"33"=>2]
</code>
Copy after login
Copy after login

当我用 

<code>$return=array_map(function($v,$k){
    //TODO
},$myarr,array_keys($myarr));
</code>
Copy after login
Copy after login

$return 怎么保持原来的key呢?

我发现,对于

<code>array_map(function($v){
    //TODO
},$myarr);
</code>
Copy after login
Copy after login

它是可以保持key的.

回复内容:

Hi ,all

<code>$myarr=["22"=>1,"33"=>2]
</code>
Copy after login
Copy after login

当我用 

<code>$return=array_map(function($v,$k){
    //TODO
},$myarr,array_keys($myarr));
</code>
Copy after login
Copy after login

$return 怎么保持原来的key呢?

我发现,对于

<code>array_map(function($v){
    //TODO
},$myarr);
</code>
Copy after login
Copy after login

它是可以保持key的.

array_map()这个函数当回调函数里面只有一个参数(即只有一个数组时),回调函数单独对这个数组的值进行操作,也可以返回键,但array_map()操作两个数组时,你还要返回键?仔细想一想也不可能,函数是给你返回第一个数组的键呢?还是第二个数组的键呢?所以多个数组就不给你键了,只给你返回值……
1 想问的是,你是想实现什么样的功能呢?
2 如果想保存第一个数组的键值,你可以这样:

<code>$arr1 = array('b' => 'banana', 'g' => 'grage');
$arr2 = array('a' => 'apple', 'p' => 'pear');
$return = array_map(function($a, $b){
    // to do something
    return 'I love ' . $a . ' and ' . $b;
}, $arr1, $arr2);
$return = array_combine(array_keys($arr1), $return);
</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