Skip to content
Advertisement

How to iterate trhough Facebook LeadAd Array in PHP?

I do Facebook Lead Ads and I’m trying to create a PHP script that iterates through the array of data that Facebook sends.

The problem is that the array may contain multiple “entry” entries. So I need to iterate through the array and for every entry take some action.

This is an example of the array that I get:

Array
(
    [object] => page
    [entry] => Array
        (
            [0] => Array
                (
                    [id] => 486382132468113
                    [time] => 1597838601
                    [changes] => Array
                        (
                            [0] => Array
                                (
                                    [value] => Array
                                        (
                                            [form_id] => 388595733337796
                                            [leadgen_id] => 634975333342066
                                            [created_time] => 1597838600
                                            [page_id] => 486382333368113
                                        )
                                    [field] => leadgen
                                )
                        )
                )
        )
)

So I thought of something like this:

foreach ($array as $element) {
  foreach ($element['entry']  {
    echo "Time:". $element['entry']['time'] . "<br>" ;
    echo "Lead ID:". $element['entry']['changes']['leadgen_id'] . "<br>" ;
  }
}

But it doesn’t work. Any help would be much appreciated.

Advertisement

Answer

Refer to the documentation foreach should be according to the following syntaxe:

foreach (array_expression as [$key =>] $value)
  statement

this simple code will help you :

<?php

$array = array
(
    "object" => "page",
    "entry" => array( array (
                    "id" => 486382132468113,
                    "time" => 1597838601,
                    "changes" => array ( array (
                                    "value" => array
                                        (
                                            "form_id" => 388595733337796,
                                            "leadgen_id" => 634975333342066,
                                            "created_time" => 1597838600,
                                            "page_id" => 486382333368113
                                        ),
                                    "field" => "leadgen"
                                )
                        )
                )
        )
);
              
foreach ($array["entry"] as $entry) {
    
    echo "Time:". $entry['time'] . "<br>" ;
  foreach ($entry['changes'] as $change) {
    
    echo "Lead ID:". $change['value']['leadgen_id'] . "<br>" ;
  }
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement