Home > Backend Development > PHP Tutorial > 数组遍历问题。

数组遍历问题。

WBOY
Release: 2016-06-23 13:26:13
Original
1082 people have browsed it

有一个数组为:

$arr = array(	'userId'=>array(1,2,3),	'username'=>array('Tom','Rose','Ben'),	'sex'=>array('男','女','男'));
Copy after login


如何把该数组转化为:
  $arr2 =array(       array('userId'=>1,'username'=>'Tom','sex'=>'男'),       array('userId'=>2,'username'=>'Rose','sex'=>'女'),       array('userId'=>3,'username'=>'Ben','sex'=>'男')   ); 
Copy after login

脑子一下子转不过来了


回复讨论(解决方案)

刚发发完贴就想到了解决办法了……

$arr = array(    'userId'=>array(1,2,3),    'username'=>array('Tom','Rose','Ben'),    'sex'=>array('男','女','男'));foreach($arr as $k=>$item) {  foreach($item as $i=>$v) $res[$i][$k] = $v;}print_r($res);
Copy after login
Array(    [0] => Array        (            [userId] => 1            [username] => Tom            [sex] => 男        )    [1] => Array        (            [userId] => 2            [username] => Rose            [sex] => 女        )    [2] => Array        (            [userId] => 3            [username] => Ben            [sex] => 男        ))
Copy after login

另类一点,就是

$arr = array(    'userId'=>array(1,2,3),    'username'=>array('Tom','Rose','Ben'),    'sex'=>array('男','女','男'));$k = array_fill(0, count($arr), array_keys($arr));$v = call_user_func_array('array_map', array_merge(array(null), $arr));$r = array_map('array_combine', $k, $v);print_r($r);
Copy after login
Copy after login

另类一点,就是

$arr = array(    'userId'=>array(1,2,3),    'username'=>array('Tom','Rose','Ben'),    'sex'=>array('男','女','男'));$k = array_fill(0, count($arr), array_keys($arr));$v = call_user_func_array('array_map', array_merge(array(null), $arr));$r = array_map('array_combine', $k, $v);print_r($r);
Copy after login
Copy after login


明白了,谢谢版主~~
Related labels:
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