skip to Main Content

i have the following Array Structure from Facebook Graph API response.

  "data": [
    {
      "actions": [
        {
          "action_type": "comment",
          "value": "2"
        },
        {
          "action_type": "offsite_conversion",
          "value": "1606"
        }
      ],
      "date_start": "2017-04-03",
      "date_stop": "2017-05-02"
    },
    {
      "actions": [

        {
          "action_type": "post",
          "value": "2"
        },
        {
          "action_type": "post_reaction",
          "value": "33"
        },
        {
          "action_type": "page_engagement",
          "value": "816"
        },
        {
          "action_type": "post_engagement",
          "value": "807"
        },
        {
          "action_type": "offsite_conversion",
          "value": "1523"
        }
      ],
      "date_start": "2017-04-03",
      "date_stop": "2017-05-02"
    },
]

The Number of values is flexible and i want to get the value from “offsite_conversion”. Normally i would do it for example like that:

data['data'][0]['actions']['1']['value']

But in that case this doesn’t work because [‘1’] is variable.

5

Answers


  1. So not completely clear what are you trying to achieve, but in a simple way you can just iterate over your $data array:

    $needed_values = array();
    foreach ($data['data'] as $item) {
        foreach ($item['actions'] as $action) {
            if ($action['action_type'] == 'offsite_conversion') {
                $needed_values[] = $action['value'];
            }
        }
    }
    
    Login or Signup to reply.
  2. Pretend $json holds the data from facebook

    <?php
    $data = json_decode($json);
    $conversions = 0;
    foreach ($data as $datum) {
      foreach ($datum['actions'] as $action) {
        if ($action['action_type'] === 'offsite_convserion') {
          $conversions += (int)$action['value'];
          break;
        }
      }
    }
    
    Login or Signup to reply.
  3. because “offsite_conversions” is always the last

    If $data['data'][0]['actions'][LAST VALUE]['value'] is what you’re looking for:

    Your idea of counting should work then:

    $actions = $data['data'][0]['actions'];
    $index = count($actions) - 1;
    
    $value = $actions[$index]['value'];
    
    Login or Signup to reply.
  4. Use a loop and test the action type.

    foreach ($data['data'][0]['actions'] as $action) {
        if ($action['action_type'] == 'offsite_conversion') {
            $result = $data['value'];
            break;
        }
    }
    
    Login or Signup to reply.
  5. Barmar has the best approach if you don’t know where it is, but it’s much easier if you want the last one:

    $result = end($data['data'][0]['actions'])['value'];
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search