user2413244
user2413244

Reputation: 241

PHP: get data from json array without loop

I have data i want to get from array without loop.

I want to get "value" of "link_click" for example, how can i make this work?

I tried: but this not working.

$stats = json_decode($data, false);
$link_click= $stats->data->actions->action_type->['link_click']->value;


{
   "data": [
      {
         "actions": [
            {
               "action_type": "comment",
               "value": 2
            },
            {
               "action_type": "link_click",
               "value": 636
            },
            {
               "action_type": "post_like",
               "value": 2
            },
            {
               "action_type": "page_engagement",
               "value": 640
            },
            {
               "action_type": "post_engagement",
               "value": 640
            }
         ],

Upvotes: 2

Views: 1451

Answers (2)

user5220291
user5220291

Reputation:

The only way you can make it possible only if you know the index of the action_type:link_click. If you know the index, you can do it by. (Answer is with respect to the data you have shown above).

$stats = json_decode($data, true);
$link_click= $stats['data']['actions'][1]['value'];

Loop example (on request):

$stats = json_decode($data, true);
$value = 0;
foreach($stats['data']['actions'] as $action) {
    if ($action->action_type == 'link_click') {
        $value = $action->value;
    }    
}

echo $value; //This is your value

Upvotes: 2

Diego Fu
Diego Fu

Reputation: 420

You can use something like JsonPath to get the value

Upvotes: 0

Related Questions