0

This shouldn't be confusing me as much as it is but I am looking to turn this:

array:3 [▼
  "subject" => array:2 [▼
        0 => "math"
        1 => "english"
  ]
 "grade" => array:2 [▼
      0 => "a"
      1 => "b"
  ]
  "received" => array:2 [▼
      0 => "2017"
      1 => "2016"
  ]
]

into this:

array:2 [▼
  "0" => array:3 [▼
    "subject" => "math"
    "grade" => "a"
    "received" => "2017"
  ]
  "1" => array:3 [▼
    "subject" => "english"
    "grade" => "b"
    "received" => "2016"
  ]
]

Tried looping through in a couple different ways but never seem to get the result I am looking for, any help would be much appreciated!

1
  • How about you show one of the loops? Commented May 23, 2018 at 15:34

2 Answers 2

4
$keys = array_keys($array);
$result = array_map(
    function (...$values) use ($keys) { return array_combine($keys, $values); }, 
    ...array_values($array)
);

Which is essentially this, but less repetitive:

array_map(
    function ($subject, $grade, $received) {
        return [
            'subject' => $subject,
            'grade' => $grade, 
            'received' => $received
        ];
    },
    $array['subject'],
    $array['grade'],
    $array['received']
)

See the manual for array_map and ... for more explanation.

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

1 Comment

First way threw an error "array_combine(): Both parameters should have an equal number of elements" however 2nd answer worked perfectly, Thanks @deceze
1

simple Version:

$arr1 = array(...);
$arr2 = array();

foreach ($arr1 as $k => $v) {
    foreach ($v as $x => $y) {
        $arr2[$x][$k] = $y;
    }
}

But you should add conditions, if the array element not exists, create it, or you may get Errors, depending on your PHP configuration.

1 Comment

Are you referring to $arr2[$x][$k] = ... creating errors? No, it never will. Implicit intermediate array creation is explicitly supported.

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.