【发布时间】:2020-07-22 09:24:36
【问题描述】:
我在这样的对象中尝试 foreach:
$data = '{
"purchase_country": "'.$this->session->data['payment_address']['iso_code_2'].'",
"purchase_currency": "'.$this->session->data['currency'].'",
"locale": "'.$this->session->data['language'].'",
"order_amount": '.$total.',
"order_tax_amount": 0,
"order_lines": [{
'. foreach ($this->cart->getProducts() as $product) { .'
"reference": "19-402",
"name": "'.$product['name'].'",
"quantity": 1,
"unit_price": 210,
"tax_rate": 0,
"total_amount": 210,
"total_tax_amount": 0,
"image_url": "https://www.exampleobjects.com/logo.png",
"product_url": "https://www.estore.com/products/f2a8d7e34",
'.}.'
}]
}';
但似乎语法不正确。我收到了 Parse 错误:语法错误,意外的 'foreach' (T_FOREACH)
对象中是否可以使用 foreach?
【问题讨论】:
-
您不能在变量中执行 foreach。您正在尝试将字符串与 foreach 连接
-
好的,但是我怎样才能用数据填充 order_lines 呢?你有例子吗?
-
构建一个多维数组并使用json_encode,这比像这样连接字符串要容易得多。