1

I have an array containing individual arrays (pulled from db) with content similar to this:

Array
(
[0] => Array
    (
        [date] => 2014-11
        [time] => 2135
        [name] => John
    )

[1] => Array
    (
        [date] => 2014-11
        [time] => 5496
        [name] => Adam
    )

[2] => Array
    (
        [date] => 2014-12
        [time] => 1526
        [name] => John
    )

[3] => Array
    (
        [date] => 2014-12
        [time] => 5481
        [name] => Adam
    )
[4] => Array
    (
        [date] => 2014-12
        [time] => 3476
        [name] => Lizzie
    )
)

What I would like to do is to build up a new multi dimensional array based on the previous array, where array's with the same month are joined together in the following way:

Array
(
[0] => Array
    (
        [date] => 2014-11
        [John] => 2135
        [Adam] => 5496
    )

[1] => Array
    (
        [date] => 2014-12
        [John] => 1526
        [Adam] => 5481
        [Lizzie] => 3476
    )
)

I have tried to look at various array functions, but simply can't get my around on how to achieve this....

1 Answer 1

1

Have a look into the following snippet.

$output = array(); // Where the output will be saved

foreach ($input as $row) { // Need to process the original input array

    $date = $row['date']; // Grouping by the date value, thus we use it as an index in an associative array

    if (empty($output[$date])) {
        $output[$date] = array('date' => $date); // Make sure the 'date' value is in the final output
    }

    $output[$date][$row['name']] = $row['time']; // Actual values, e.g., [Adam] => 5496
} 

$output = array_values($output); // Removing original indexes from the associative array

The desired array structure in the question is kinda strange but no question asked.

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

1 Comment

Thanks for the detailed suggestion! It works as advertised. The reason that I want the array like that is because the data is going to be used for a stacked bar chart, and as I see it this would be the best format to feed to the Google API. I'm definitely very open other suggestions if any. I'm by far a very noob PHP developer, which probably also is mirrored in my way of thinking :-)

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.