Trouble accessing an array

Published 8 months ago by gregghoush

I am attempting to use Rob Brazier's Laravel-Piwik package to grab information from my Piwik install. I have this code to get visits to blog posts in the past week. It gives me an object, which contains an array, which is made up of objects.

        $visits = Piwik::getActions();
        $visits = $visits->getPageUrls(['period' => 'week', 'expanded' => '1', 'segment' => 'pageUrl%3D%5Ehttp%253A%252F%252Ftesting.dev%252Fblog%252F']);
        //$visits = $visits->subtable[0];
        dd($visits);

This works, it gets me the object and the dd shows it to me.

Here is the object it gives me: http://i.imgur.com/2o9TVpi.png

If I uncomment the commented out line there I get this error: Trying to get property "subtable" of non-object.

How do I access that array "subtable"? I would like to loop through it with a foreach.

Best Answer (As Selected By gregghoush)
Jaytee

Not sure why you need the index, but that's PHP for you lol.

If you don't like that approach, just turn it into a collection.

$visits = collect($visits->getPageUrls(['period' => 'week', 'expanded' => '1', 'segment' => 'pageUrl%3D%5Ehttp%253A%252F%252Ftesting.dev%252Fblog%252F']));
Dry7
Dry7
8 months ago (151,680 XP)

@gregghoush maybe

$visits = $visits['subtable'][0];

?

gregghoush

Hey @Dry7,

Thanks, tried that just now, it gives me this error:

Undefined index: subtable

ftrillo

Are you sure $visits is an object or an array? It might be a JSON string, and then you might need json_decode() before accessing anything in it.

gregghoush

Thanks @ftrillo, typeof tells me its an Array and passing $visits to json_decode says json_decode() expects parameter 1 to be string, array given

ftrillo

Weird. Could you iterate through the array and print the keys?

Someone who actually knows how Laravel-Piwik works is gonna see this discussion and laugh his ass off.

Cronix
Cronix
8 months ago (481,440 XP)

Does dd($visits->subtable) give you the subtable array?

gregghoush

Turns out this is how I get just the array from subtable:

$visits = $visits[0]->subtable;

Jaytee
Jaytee
8 months ago (103,905 XP)

Not sure why you need the index, but that's PHP for you lol.

If you don't like that approach, just turn it into a collection.

$visits = collect($visits->getPageUrls(['period' => 'week', 'expanded' => '1', 'segment' => 'pageUrl%3D%5Ehttp%253A%252F%252Ftesting.dev%252Fblog%252F']));

Please sign in or create an account to participate in this conversation.