3

I have an array data that look like this :

Array (
    [0] => Array (
        [0] => Name:
        [1] => John W.
        [2] => Registration ID:
        [3] => 36
    ) 
    [1] => Array (
        [0] =>Age:
        [1] => 35
        [2] => Height:
        [3] => 5'11"
    ) 
    [3] => Array (
        [0] => Sex:
        [1] => M
        [2] => Weight:
        [3] => 200lbs
    )
    [4] => Array (
        [0] => Address
    )
    [5] => Array (
        [0] => 6824 crestwood dr delphi, IN 46923
    ))

And I want to convert it to associative array like this :

Array(
    ['Name']=> John W.
    ['Registration ID']=> 36
    ['Age']=> 35
    ['Height'] => 5'11''
    ['Sex']=>M
    ['Weight']=>200lbs
    ['Address']=>6824 crestwood dr delphi, IN 46923
)

I have no idea at all how to do this, since the supposed to be array column header were also in sequence, so it makes difficult to convert this array.

Any help I appreciate, thx.

2 Answers 2

2

Given your origin array is called $origin , you can do it like this:

$merged = array();
foreach($origin as $val) {
   $merged = array_merge($merged, $val);
}
$tot = count($merged) - 1;
for ($i=0;$i<$tot;$i+=2) {
   $result[$merged[$i]] = $merged[$i+1];
}

var_dump($result); // To test the resulting array

Firstly, I use array_merge() to flatten the $origin array to only one dimension/depth, so we later iterate it (stepping each 2 items per iteration) and assigning each pair of items ($i and $i+1) to the resulting array.

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

1 Comment

Thank you very much its work. Why I can't come up with this simple way? Thx again.
1

Looks like, for the first 3 children, you can just assign the even value to the previous element as key. Then, assign the fourth one as key for fifth element.

   $result = array();
   foreach ($array as $key => $value)
   {
       if ($key < 4) {
             $elements = array_values($value);
             $result[$elements[0]] = $elements[1];
             $result[$elements[2]] = $elements[3];
        }

        if ($key == 4)
             $fifthkey = $value;

         if ($key == 5)
             $result[$fifthkey] = $value;
    }

Also, note that you have to escape your height string quotes.

1 Comment

Thank you for the solution, but actually the data are larger than what I have wrote above, so I think it wouldn't be efficient if I define which child is the key and which is the related value.

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.