PHP: get data from json array without loop

2020-04-17 05:30发布

问题:

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
            }
         ],

回答1:

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


回答2:

You can use something like JsonPath to get the value



标签: php arrays json