如何在循环中生成多级关联数组



我需要传入一个行项目数组来使用Stripe生成发票。最终结果应该是这样的:注意line_items部分。

$checkout_session = StripeCheckoutSession::create([
'payment_method_types' => ['card'],
'line_items' => [['quantity' => 1,
'price_data' => ['currency' => 'CAD',
'unit_amount' => 750,
'product_data' => ['name' => 'Name goes here',
'description' => 'Description goes here']]],
['quantity' => 1,
'price_data' => ['currency' => 'CAD',
'unit_amount' => 450,
'product_data' => ['name' => 'Name goes here',
'description' => 'Description goes here']]]
],
'mode' => 'payment',
'success_url' => $YOUR_DOMAIN.'/success.htm',
'cancel_url' => $YOUR_DOMAIN.'/cancel.htm',
]);

在本例中,有两个行项目,但可以有任意数量的项目。当然,问题是,在传入之前,我需要生成这个行项目数组,而这些行项目是从DB中出来的。

因此,理想情况下,我可以在一个变量中生成line_items数组,然后只传入该变量;像这样:

$checkout_session = StripeCheckoutSession::create([
'payment_method_types' => ['card'],
'line_items' => [$lineitems],
'mode' => 'payment',
'success_url' => $YOUR_DOMAIN.'/success.htm',
'cancel_url' => $YOUR_DOMAIN.'/cancel.htm',
]);

然而,到目前为止,没有运气。我可以在循环中生成一个字符串,如下所示:

foreach($rows as $row){
$linedescription = $row["itemname"];
$lineamount = $row["amount"];
$linecomment = $row["comment"];
$lineamount = $lineamount * 100;
if($index > 0){
$lineitems .= ",";
}
$lineitems = "['quantity' => 1,'price_data' => ['currency' => '".$currencycode."','unit_amount' => ".$lineamount.", 'product_data' => ['name' => '".$linecomment."','description' => '".$linedescription."']]]";
$index ++;
}

这正是我的答案:

"[['quantity' => 1,
'price_data' => ['currency' => 'CAD',
'unit_amount' => 750,
'product_data' => ['name' => 'Name goes here',
'description' => 'Description goes here']]],
['quantity' => 1,
'price_data' => ['currency' => 'CAD',
'unit_amount' => 450,
'product_data' => ['name' => 'Name goes here',
'description' => 'Description goes here']]]
]"

问题是,这是一个字符串,我需要它是一个数组。我尝试过json_decode,也尝试过在循环中生成一个数组而不是字符串,但我似乎无法得到我需要的东西。肯定有一个简单的方法可以做到这一点吗?

您可以像构建字符串一样构建数组。为了可读性,我将每个维度拆分为一行单独的代码,但如果需要,可以将它们合并为一行:

$lineitems = array();
foreach ($rows as $row) {
$product_data = array('name' => $row["comment"],
'description' => $row["itemname"]
);
$price_data = array('currency' => $currencycode,
'unit_amount' => $row["amount"],
'product_data' => $product_data
);
$lineitem = array('quantity' => 1,
'price_data' => $price_data
);
$lineitems[] = $lineitem;
}

然后你可以简单地使用:

'line_items' => $lineitems,

在您对StripeCheckoutSession::create的呼叫中。

请注意,如果没有用于测试的示例数据,则很难确定,但此代码应该按预期工作。还要注意,从名称中可以看出,也许name条目应该是$row['itemname'],而description应该是$row['comment']

最新更新