如何在多维数组内插入foreach循环?
我有一个多维数组,可用于将网站连接到Mailchimp。我必须使用foreach循环检查用户购买的产品数量,然后将这些添加到一个数组中,称为“ lines”。
此刻是我的json代码,在我发送给Mailchimp之后:
$json_data = '{
"id": "2'. $order->id .'",
"customer": {
"id": "71",
"email_address": "'.$order->email.'",
"opt_in_status": true,
"company": "'.$order->company_name.'",
"first_name": "'.$order->pad_firstname.'",
"last_name": "'.$order->pad_lastname.'",
"orders_count": 1,
"total_spent": 86
},
"checkout_url": "https://www.mywebsite.it/en/checkout/confirmation/",
"currency_code": "EUR",
"order_total": 86,
"lines"[{
'.$line_result.'
}]
}';
$ line_result 是我尝试添加产品系列的地方。 我知道错了。
“行”内的所有数组都需要像这样:
"lines":[
{
data product 1 ...
},
{
data product 2 ...
}
]
这是我的前途
foreach ($order->pad_products as $product) {
$line_result['line'] = array(
"id" => "$order->id",
"product_id" => "$product->pad_product_id",
"product_title" => "$product->title",
"product_variant_id" => "$product->id",
"product_variant_title" => "$product->title",
"quantity" => "$product->pad_quantity",
"price" => "$product->prezzo",
);
};
什么是插入此数据并创建像我所需的多维数组的正确方法? 谢谢。
答案 0 :(得分:2)
您只需要将所有$ line_result存储在全局变量中,然后将其绑定到您的json模型:
$results = [];
foreach ($order->pad_products as $product) {
$results[] = array(
"id" => $order->id,
"product_id" => $product->pad_product_id,
"product_title" => $product->title,
"product_variant_id" => $product->id,
"product_variant_title" => $product->title,
"quantity" => $product->pad_quantity,
"price" => $product->prezzo,
);
};
$data = json_decode($json_data, true);
$data['lines'] = $results;
$json = json_encode($data);
编辑:脚本数组转换为json
$lines = [];
foreach ($order->pad_products as $product) {
$lines[] = array(
"id" => $order->id,
"product_id" => $product->pad_product_id,
"product_title" => $product->title,
"product_variant_id" => $product->id,
"product_variant_title" => $product->title,
"quantity" => $product->pad_quantity,
"price" => $product->prezzo,
);
}
$data = [
'id' => '2'.$order->id,
'customer' => [
'id' => '71',
'email_address' => $order->email,
'opt_in_status' => true,
'company' => $order->company_name,
'first_name' => $order->pad_firstname,
'last_name' => $order->pad_lastname,
'orders_count' => 1,
'total_spent' => 86
],
'checkout_url' => 'https://www.mywebsite.it/en/checkout/confirmation',
'currency_code' => 'EUR',
'order_total' => 86,
'lines' => $lines
];
$jsonData = json_encode($data, JSON_UNESCAPED_UNICODE);
答案 1 :(得分:0)
我想对@adrianRosi表示感谢,感谢他给我的帮助和帮助。
最后,我找到了解决方案,它是json_encode
数组,然后以json格式添加到$ data中。
以这种方式:
$product_list = [];
foreach ($order->pad_products as $product) {
$product_list[] = array(
"id" => "$id",
"..." => "...",
);
};
$data_products['lines'] = $product_list;
$json_products = json_encode($data_products);
$json_products_edit = substr($json_products, 1, -1); // to delete the {}
$prezzo_totale = $order->pad_price_total;
$json_data = '{
...
...
'.$json_products_edit.'
}';