我使用facebook api制作一个flexible_spec定位数组。我在阵列中有三个选项。第一个是必需的,其他是可选的。
所以我试图根据变量是否通过$ _GET传递来构建一个数组。
最终数组应如下所示:
["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) ""
}
}
第一个兴趣数组将始终出现,但是如果$ _GET响应不是一个空数组,那么应该构造第二个和第三个数组(我可能会在这里使事情复杂化我确定!)
所以我的代码看起来像这样但返回错误,因为它标识数组没有关闭(缺少半冒号和逗号在不正确的地方)
$flex_array = array(
array(
'interests' => $interests
),
if (!empty($mustinterests)) {
array(
'interests' => $mustinterests
),
}
if (!empty($excludeinterests)) {
array(
'exclusions' => $excludeinterests
)
}
);
然后在$ 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,
));
我无法想到构建数组的更好的过程吗?
答案 0 :(得分:1)
您不能在数组定义中使用if语句。这是语法错误。您可以使用单独的语句构建所需的数组。
$flex_array = array(array('interests' => $interests));
if (!empty($mustinterests)) {
$flex_array[] = array('interests' => $mustinterests);
}
if (!empty($excludeinterests)) {
$flex_array[] = array('exclusions' => $excludeinterests);
}
答案 1 :(得分:0)
确保不要在数组中放置if语句!