我一直在阅读,找不到符合我要求的解决方案。我需要动态地将值添加到'添加'这个数组的一部分取决于条件。我知道你不能在数组本身内放置任何if
语句。
正确的语法(来自文档)是:
$subResult = $gateway->subscription()->create([
'paymentMethodToken' => 'the_token',
'planId' => 'thePlanId',
'addOns' => [
'add' => [
[
'inheritedFromId' => 'addon1',
'amount' => '10'
],
[
'inheritedFromId' => 'addon2',
'amount' => '10'
]
]
]
]);
根据我在SO上的类似问题上所阅读的内容,我尝试了以下内容(其中$ addon1和$ addon2将是代码中先前设置的条件)
$addon1 = true;
$addon2 = true;
$subResult = $gateway->subscription()->create([
'paymentMethodToken' => 'the_token',
'planId' => 'thePlanId',
'addOns' => [
'add' => [
($addon1 ? array(
[
'inheritedFromId' => 'productAddon1Id',
'amount' => '10'
]) : false),
($addon2 ? array(
[
'inheritedFromId' => 'productAddon2Id',
'amount' => '10'
]) : false)
]
]
]);
但是我回来了Warning: XMLWriter::startElement(): Invalid Element Name
所以我怀疑它不喜欢结构,代码失败并发生致命错误(有趣的是,如果我只将第一个$ addon设置为true,它仍然会出现警告,但确实有效。有两个失败了。)
还有其他方法可以做到这一点,还是我的语法错误了?
由于可能的产品组合数量,我无法对所有可能性进行硬编码。
会感激和帮助。谢谢。
答案 0 :(得分:2)
不要试图一次完成所有事情。
$add = [];
if( $addon1)
$add[] = ['inheritedFromId'=>.......];
if( $addon2)
.....
$subResult = $gateway->subscription()->create([
'paymentMethodToken' => 'the_token',
'planId' => 'thePlanId',
'addOns' => [
'add' => $add
]
]);
答案 1 :(得分:1)
你可以将if语句放在数组声明中,它叫做三元操作:
$myArray['key'] = ($foo == 'bar' ? 1 : 2);
这是如何使用的基础。
答案 2 :(得分:1)
您正在使用array()
语法和短数组语法([]
)。见the manual。这意味着,例如add
中的第一个元素是数组中的数组。也许这就是XML错误发生的原因?更好的是:
'add' => [
($addon1 ?
[
'inheritedFromId' => 'productAddon1Id',
'amount' => '10'
] : null),
($addon2 ?
[
'inheritedFromId' => 'productAddon2Id',
'amount' => '10'
] : null)
]
]
答案 3 :(得分:0)
你的语法很好。您正在使用此结构创建数组
array (size=3)
'paymentMethodToken' => string 'the_token'
(length=9)
'planId' => string 'thePlanId'
(length=9)
'addOns' =>
array (size=1)
'add' =>
array (size=2)
0 =>
array (size=1)
...
1 =>
array (size=1)
...
我的问题是$ gateway-> subscription() - > create()不喜欢你的数组结构。也许'false'作为值或数字键。检查它的期望,然后使用阵列的新结构重试。