PHP:如何使用内置函数处理数组的键值

WBOY
Release: 2016-06-06 20:45:11
Original
983 people have browsed it

需求

<code>$tempArray = array(
    0=>"1:A",
    1=>"2:B",
    2=>"3:C",
    3=>"4:D",
    4=>"5:E",
);
</code>
Copy after login
Copy after login

转成:

<code>$tempArray = array(
    "A"=>1,
    "B"=>2,
    "C"=>3,
    "D"=>4,
    "E"=>5,                 
);
</code>
Copy after login
Copy after login

本来想使用php的内置函数array_map来处理的,但是没有成功,除了遍历之外,我更想直接使用php的内置函数来实现,请问代码应该怎么写呢?

回复内容:

需求

<code>$tempArray = array(
    0=>"1:A",
    1=>"2:B",
    2=>"3:C",
    3=>"4:D",
    4=>"5:E",
);
</code>
Copy after login
Copy after login

转成:

<code>$tempArray = array(
    "A"=>1,
    "B"=>2,
    "C"=>3,
    "D"=>4,
    "E"=>5,                 
);
</code>
Copy after login
Copy after login

本来想使用php的内置函数array_map来处理的,但是没有成功,除了遍历之外,我更想直接使用php的内置函数来实现,请问代码应该怎么写呢?

一定要用array_map(不支持key),这是一个方法.

<code>$tempArray = array(
    0=>"1:A",
    1=>"2:B",
    2=>"3:C",
    3=>"4:D",
    4=>"5:E",
);

$result = array();

array_map(function($value) use (&$result) {
    list($k,$v) = explode(":", $value);
    $result[$k] = $v;
},$tempArray);
</code>
Copy after login

<code>$array = array(
    0=>"1:A",
    1=>"2:B",
    2=>"3:C",
    3=>"4:D",
    4=>"5:E",
);
//处理
$array1 = array();
array_walk($array, function($val,$key,$fix) use(&$array1){ 
    $v = explode($fix, $val);
    $array1[$v[1]] = $v[0];   
},':');
var_dump($array1); 
/* 输出
array (size=5)
  'A' => string '1' (length=1)
  'B' => string '2' (length=1)
  'C' => string '3' (length=1)
  'D' => string '4' (length=1)
  'E' => string '5' (length=1)
*/
</code>
Copy after login

补充:

<code>array_walk($array, function($val,$key,$arr){ 
    $v = explode(":", $val);
    $arr[0][$v[1]] = $v[0];   
},array(&$array1));
</code>
Copy after login

这么处理也是可以的

<code>$arr = ["1:A", "2:B", "3:C", "4:D", "5:E"];

$arr = json_decode("{".implode(',', array_map(function($item){
    return preg_replace('/(.+?):(.+?)/', '"$2":"$1"', $item);
}, $arr))."}", true);
print_r($arr);
/** output
Array
(
    [A] => 1
    [B] => 2
    [C] => 3
    [D] => 4
    [E] => 5
)
**/
</code>
Copy after login

如果值里头的:唯一的话可以这么做,为了显得狂拽一点缩成一句话了,可能有点难看懂。

array_mapexplode拆冒号
array_combine拼接

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!