tomantford tomantford - 6 months ago 20
PHP Question

Building an array from $_GET Data

I'm using facebook api to make a flexible_spec targeting array. I have three options in the array. The first is required, the others are optional.

So I'm trying to build an array based on if the variable is passed through $_GET.

The final array should look like this:

["flexible_spec"]=>
array(3) {
[0]=>
array(1) {
["interests"]=>
array(1) {
[0]=>
string(13) "6003220643158"
}
}
[1]=>
array(1) {
["interests"]=>
array(1) {
[0]=>
string(13) "6002866944422"
}
}
[2]=>
array(1) {
["exclusions"]=>
array(1) {
[0]=>
string(0) ""
}
}


The first interest array will always appear, but the second and third should be constructed if the $_GET response is not an empty array (I could be over complicating things here I'm sure!)

So my code looks like this but returns errors as it identifies the array is not closed (missing semi colons and commas in incorrect places)

$flex_array = array(
array(
'interests' => $interests
),

if (!empty($mustinterests)) {
array(
'interests' => $mustinterests
),
}
if (!empty($excludeinterests)) {
array(
'exclusions' => $excludeinterests
)
}

);


This array is then called within $reach_estimate:

$targeting_spec = array(
'geo_locations' => array(
'countries' => ['GB'],
),
'page_types' => $pieces,

'flexible_spec' => $flex_array
);
$reach_estimate = $account->getReachEstimate(
array(),
array(
'currency' => 'GBP',
'optimize_for' => $OptimizationGoal,
'targeting_spec' => $targeting_spec,
));


I can't think of a better process than this to build the array?

Answer

You cannot use an if statement within an array definition. This is a syntax error. You can build the array you want using separate statements instead.

$flex_array = array(array('interests' => $interests));

if (!empty($mustinterests)) {
    $flex_array[] = array('interests' => $mustinterests);
}

if (!empty($excludeinterests)) {
    $flex_array[] = array('exclusions' => $excludeinterests);
}