Dharmesh
Dharmesh

Reputation: 42

Searching and retrieving the data from multidimensional array

I have a multidimensional array (of Google Analytics data), like the below:

Array
(
[0] => gapiReportEntry Object
    (
        [metrics:gapiReportEntry:private] => Array
            (
                [uniquePageviews] => 1
                [visitors] => 1
                [pageviews] => 1
            )

        [dimensions:gapiReportEntry:private] => Array
            (
                [pagePath] => /107483
            )

    )

[1] => gapiReportEntry Object
    (
        [metrics:gapiReportEntry:private] => Array
            (
                [uniquePageviews] => 1
                [visitors] => 1
                [pageviews] => 1
            )

        [dimensions:gapiReportEntry:private] => Array
            (
                [pagePath] => /754985
            )

    )

What I am trying to do is search the array to see if a match is found in the [pagePath] element based on some entries in my database. If a match is found, I want to print the [visitors] from within that array. If a match isn't found I want to return a number of 0.

This is not correct, but hopefully illustrates what I am trying to achieve:

<?php
if(in_array($value['Identifier'],$metrics['pagePath')) {
$metrics['pagePath')
}else{
echo "0";
}   
?>

Overall, what I am trying to achieve is a table of data based on pages on website and the corresponding analytics results.

Upvotes: 0

Views: 229

Answers (1)

Mike Brant
Mike Brant

Reputation: 71384

You may find help in array_filter() function. This will allow you to filter your array of objects based on a specific criteria. An example might look like this:

$page_path = '/12345'; // the page path you are interested in
$metrics = ...; // your array of objects

$filtered_array = array_filter($metrics, function ($item) use $page_path {
    return ($item['dimensions:gapiReportEntry:private']['pagePath'] == $page_path);
}

You now have the only the objects with matching page paths in $filtered_array.

You can iterate that array and pull out all visitors info like this:

$visitors = array();
foreach($filtered_array as $item) {
    $visitors[] = $item['metrics:gapiReportEntry:private']['visitors'];
}

Upvotes: 1

Related Questions