2

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
            }
         ],
5
  • This sounds a lot like a homework assignment. Please post what you have tried. This is not a code generation site! Commented Aug 12, 2015 at 16:47
  • Since all your action entries have the action_type, you will need to loop over them and add a conditional to check against its value being "link_click". Better question: Why is looping not an option in this case? Commented Aug 12, 2015 at 16:48
  • 1
    @nLee, this code come from facebook api i tried to get the data using: '$link_click= $stats->data->actions->action_type->['link_click']->value;' Commented Aug 12, 2015 at 16:48
  • @Mario Wenig, can you give me example? Commented Aug 12, 2015 at 16:50
  • Look up 'foreach php' or 'php forach json array' Commented Aug 12, 2015 at 16:54

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

HI, can you give me also loop example? Thanks.
Will work, IF and ONLY IF resulting json data doesn't change. Careful trusting external data without doing your own validation on what data you are expecting.
0

You can use something like JsonPath to get the value

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.