Reputation: 1113
This code:
$arr1 = array();
for ($i=0; $i<10; $i++)
{
$arr1[] = array('A'=>rand(0,5), 'B'=>rand(0,4));
}
generates array like this:
[0] array('A'=>0,[B]=>4)
[1] array('A'=>1,[B]=>3)
[2] array('A'=>3,[B]=>1)
//etc.
I need to get the different structure, i.e.:
$arr2 = array('A' => array(0,1,3),'B' => array(4,3,1));
so that later I can use $arr2['A']
. If the array is created like it's shown in the first example, then $arr1['A']
will not work.
How can I get $arr2
using FOR loop like for $arr1
. Hope I explained myself clear enough.
Upvotes: 0
Views: 34
Reputation: 152216
Try with:
$arr2 = array(
'A' => array(),
'B' => array()
);
for ($i=0; $i<10; $i++)
{
$arr2['A'][] = rand(0,5);
$arr2['B'][] = rand(0,4);
}
If you want to convert existing $arr1
into $arr2
, try with:
$arr2 = array(
'A' => array(),
'B' => array()
);
foreach ( $arr1 as $value )
{
$arr2['A'][] = $value['A'];
$arr2['B'][] = $value['B'];
}
Upvotes: 3