Question

So I have 4 different arrays that I want to combine, because I need to encode them in JSON. I need the json_encode() output to resemble this:

[
    {

        id: 1
        user: "asd1",
        content: "Content 1",
        date: "3/12/2014 11:13 PM",

    }

]

However, I need to use a foreach loop because there are multiple entries like this. Here's an example of my arrays.

Array
(
    [id] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 4
            [4] => 5
        )

    [user] => Array
        (
            [0] => asd1
            [1] => asd2
            [2] => asd3
            [3] => asd4
            [4] => asd5
        )

    [content] => Array
        (
            [0] => Content 1
            [1] => Content 2
            [2] => Content 3
            [3] => Content 4
            [4] => Content 5
        )

    [date] => Array
        (
            [0] => 3/12/2014 11:13 PM
            [1] => 1/13/2014 11:06 PM
            [2] => 1/13/2014 3:36 PM
            [3] => 11/24/2013 3:28 PM
            [4] => 11/10/2013 1:22 AM
        )

)

I've played around with foreach loops and array_combine, but with no success. Thanks in advance.

Was it helpful?

Solution

array_map is the solution to your problem.

$source = [
    'id' => [1, 2, 3],
    'user' => ['first user', 'second user', 'third user'],
];

$result = array_map(function ($id, $user) {
    return compact('id', 'user');
}, $source['id'], $source['user']);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top