Home  >  Article  >  Backend Development  >  数组遍历问题。

数组遍历问题。

WBOY
WBOYOriginal
2016-06-23 13:26:131065browse

有一个数组为:

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


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

脑子一下子转不过来了


回复讨论(解决方案)

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

$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);
Array(    [0] => Array        (            [userId] => 1            [username] => Tom            [sex] => 男        )    [1] => Array        (            [userId] => 2            [username] => Rose            [sex] => 女        )    [2] => Array        (            [userId] => 3            [username] => Ben            [sex] => 男        ))

另类一点,就是

$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);

另类一点,就是

$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);


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