I have an array like this:
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)
}
how can I divide it into 5 separate arrays? (Actually divide the array into its length)
This is my code:
$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;
This is the output:
[[["a",1]],{"1":["b",2]},{"2":["c",3]},{"3":["d",4]},{"4":["e",5]}]
I want to have something like this: [["a",1],["b",2],["c",3],["d",4],["e",5]]
Not sure what you're trying to achieve but you can use a loop and access each array, in this example as the variable $a
. Have a read of http://php.net/manual/en/control-structures.foreach.php
foreach($arr as $a) {
//do what you want with $a
print_r($a);
}
$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 );
Result
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.