Question

How can I take a multi-dimensional array like the below, and split it into multiple separate arrays? Additional challenge: Although I know there are two pairs in the example below (pageviews, visits), how can you do it assuming that you don't know the number of pairs in the array? For example, I may want to add "time on page" or "pages visited", and could therefore have any number of pairs.

My goal, in the end, would be to have an array like: "26, 9, 18" and another array "20, 4, 9".

I've got an array like this:

Array
(
    [20090817] => Array
        (
            [ga:pageviews] => 26
            [ga:visits] => 20
        )

    [20090818] => Array
        (
            [ga:pageviews] => 9
            [ga:visits] => 4
        )

    [20090819] => Array
        (
            [ga:pageviews] => 18
            [ga:visits] => 9
        )
)

I would have thought the below code would work, but it doesn't get the specific value that I want, and for some weird reason, it trims each value to one character:

$pageViews = array();
$visits[] = array();
foreach ($google_lastMonth as $value) {
    foreach ($value as $nested_key => $nested_value) {
        $pageViews[] = $nested_value["ga:pageviews"];
        $visits[] = $nested_value["ga:visits"];
    }
}
Was it helpful?

Solution

Your array is not as deep as you think:

$pageViews = array();
$visits = array();
foreach ($google_lastMonth as $value) {
    $pageViews[] = $value["ga:pageviews"];
    $visits[] = $value["ga:visits"];
}

OTHER TIPS

I think

you should erase the braket on visit

Ok my bad should be that

  $pageViews = array();
    $visits = array();
    foreach ($result as $value) {
    $pageViews[] = $value['ga:pageviews'];
        $visits[] = $value['ga:visits'];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top