1

i have this array submitted using an extjs form:

$submittedFormaddress = array('city' => array('london', 'boston', 'paris'),
'country' => array('UK', 'USA', 'FRANCE'),
'zip' => array('22222', '33333', '44444'));

How can i automatically create below array from $submittedFormaddress?

$clientAddress=array('address1'=>array
('city'=>'london','country'=>'UK','zip'=>'2222'),'address2'=>array
('city'=>'boston','country'=>'USA','zip'=>'3333'),'address3'=>array
('city'=>'paris','country'=>'FRANCE','zip'=>'44444'));

2 Answers 2

1

I would suggest using foreach() to loop through and drill down.

I tried to make each variable name descriptive:

<?php
foreach ($submittedFormaddress as $address_part => $part_array) {
    foreach($part_array as $index => $name) {
        $clientAddress['address' . ($index + 1)][$address_part] = $name;
    }
}
?>

Working Example

Sign up to request clarification or add additional context in comments.

Comments

1
for ($i = 0; $i < count($submittedFormaddress['city']); $i++)
{
    $clientAddress['address'.$i] = array(
        'city' => $submittedFormaddress['city'][$i],
        'country' => $submittedFormaddress['country'][$i],
        'zip' => $submittedFormaddress['zip'][$i],
    );
}

3 Comments

Might I suggest you utilise array_keys to make the solution a bit less fragile
This will create array keys starting with address0, and not address1 like the OP indicated.
Thanks for your answer but please not that i don't know which form fields are submitted so i shouldn't set them manually.your code is good for understanding arrays deeper and a + for it.

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.