以 WooCommerce API 文档中的以下代码为例。我想做的是在数组中添加一些 if 条件。例如,我希望基于某些 if 条件,将 payment_details 数组作为 $data 的一部分。这可能吗?怎么办?
<?php
$data = [
'order' => [
'payment_details' => [
'method_id' => 'bacs',
'method_title' => 'Direct Bank Transfer',
'paid' => true
],
'billing_address' => [
'first_name' => 'John',
'last_name' => 'Doe',
'address_1' => '969 Market',
'address_2' => '',
'city' => 'San Francisco',
'state' => 'CA',
'postcode' => '94103',
'country' => 'US',
'email' => '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1973767177377d767c597c61787469757c377a7674" rel="noreferrer noopener nofollow">[email protected]</a>',
'phone' => '(555) 555-5555'
],
'shipping_address' => [
'first_name' => 'John',
'last_name' => 'Doe',
'address_1' => '969 Market',
'address_2' => '',
'city' => 'San Francisco',
'state' => 'CA',
'postcode' => '94103',
'country' => 'US'
],
'customer_id' => 2,
'line_items' => [
[
'product_id' => 546,
'quantity' => 2
],
[
'product_id' => 613,
'quantity' => 1,
'variations' => [
'pa_color' => 'Black'
]
]
],
'shipping_lines' => [
[
'method_id' => 'flat_rate',
'method_title' => 'Flat Rate',
'total' => 10
]
]
]
];
print_r($woocommerce->post('orders', $data));
?>
重点是,我不想再次定义整个数组,而是想在此处放置一个 if 条件:
'订单'=> [
如果($付款='xyz'){
'payment_details' => [
'method_id' => 'bacs',
'method_title' => 'Direct Bank Transfer',
'paid' => true
],
} 否则{
'payment_details' => [
'method_id' => 'monopoly',
'method_title' => 'Monopoly',
'paid' => true
],
}
是否可以使用点等于连接数组? .= 谢谢。
最佳答案
“payment_details”已经是 $data 的一部分。
要获取它,请使用:
$paymentDetails = $data['order']['payment_details'];
然后你可以用以下方式显示它:
echo $paymentDetails['method_title'];
如果你想使用if条件:
if ($paymentDetails['method_title'] === 'Monopoly money') {
echo 'That will not work';
}
要更改付款详细信息:
$data['order']['payment_details']['method_title'] = 'Changed';
或
$data['order']['payment_details'] = ['method_title' => 'something', 'method_id' => 5, 'paid' => false];
关于PHP 在数组变量中添加条件(WooCommerce API),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51033819/