在PHP中将数组划分为单独的数组

时间:2014-11-13 22:13:38

标签: php arrays

我有一个这样的数组:

array(5) { 
[0]=> array(1) 
  [0]=> int(1)       

[1]=> array(1)  
  [0]=> int(2) 

[2]=> array(1)  
  [0]=> int(3) 

[3]=> array(1)  
  [0]=> int(4)

[4]=> array(1)   
  [0]=> int(5)
   }

如何将其划分为5个独立的数组? (实际上将数组划分为长度)

这是我的代码:

$temp = array();
function toArr(){
return func_get_args();
}
//{('a',1),('b',2),('c',3),('d',4),('e',5)}
$a = array ('a','b','c','d','e');
$b = array(1,2,3,4,5);
$c = array_map ('toArr',$a,$b);

$collection1 = array_slice($c, 0, 1, true);
$collection2 = array_slice($c, 1, 1, true);
$collection3 = array_slice($c, 2, 1, true);
$collection4 = array_slice($c, 3, 1, true);
$collection5 = array_slice($c, 4, 1, true);
$temp[] = $collection1;
$temp[] = $collection2;
$temp[] = $collection3;
$temp[] = $collection4;
$temp[] = $collection5;
$jsondata = json_encode($temp); 
      echo $jsondata;

这是输出:

[[["a",1]],{"1":["b",2]},{"2":["c",3]},{"3":["d",4]},{"4":["e",5]}]

我想要这样的东西: [["",1],[" B",2],[" C",3],[" d&#34 ;, 4],[" E",5]]

2 个答案:

答案 0 :(得分:2)

不确定您要实现的目标,但您可以使用循环并访问每个数组,在此示例中为变量$a。阅读http://php.net/manual/en/control-structures.foreach.php

foreach($arr as $a) {
    //do what you want with $a
    print_r($a);
}

答案 1 :(得分:0)

$array =
    array(  
         '0' => array( '0' => 1 )
        ,'1' => array( '0' => 2 ) 
        ,'2' => array( '0' => 3 ) 
        ,'3' => array( '0' => 4 )
        ,'4' => array( '0' => 5 )
   );

foreach( $array as $key => $value )
{
    /*
     *  Variable variables
     */
    ${'array' .$key} = $value;
}

var_dump( $array0 );
var_dump( $array1 );
var_dump( $array2 );
var_dump( $array3 );
var_dump( $array4 );

结果

array (size=1)
  0 => int 1

array (size=1)
  0 => int 2

array (size=1)
  0 => int 3

array (size=1)
  0 => int 4

array (size=1)
  0 => int 5