0

I have this following array :

$myarray = array(
"key_x_1"=>"A",
"key_x_2"=>"B",
"key_x_3"=>"C",
"key_x_4"=>"A",
"key_y_1"=>"10",
"key_y_2"=>"10",
"key_y_3"=>"15",
"key_y_4"=>"20"
);

I want to create a new array like this :

 $mynewarray = array(
"A"=>array(10,20),
"B"=>array(10),
"C"=>array(15)
);

Is it possible ? How can i do this ?

1
  • In the second array ($mynewarray), keys are unique values from values from the first array that contain Key_x. The relation between key_x and key_y are the numbers in key name. Commented Dec 12, 2011 at 23:19

1 Answer 1

2

I don't know if I understand your logic, but:

$i=1;
while($i<count($myarray)) {
  if(isset($myarray['key_x'.$i]) && isset($myarray['key_y'.$i])) {
    $mynewarray[$myarray['key_x'.$i]][]=$myarray['key_y'.$i];
    ++$i;
  } else {
    break;
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

this works, but to follow his code it should be isset($myarray['key_x_'.$i]) && isset($myarray['key_y_'.$i])

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.