0

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.

2
  • What have you tried.. Firstly you're only generating 1 random number.. so, what do you think the next step would be? Btw given you have basically answered yourself :) Commented Sep 12, 2012 at 10:45
  • @BugFinder: Sorry, I still don't understand how to get the $arr2 structure from FOR loop. Commented Sep 12, 2012 at 10:47

1 Answer 1

3

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'];
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.