Maison >développement back-end >tutoriel php >数组遍历问题。
有一个数组为:
$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);