【发布时间】:2017-06-24 03:30:29
【问题描述】:
我对 PHP 和 WordPress 还是很陌生,我正在努力正确地对一个包含多个 woocommerce 订单项的数组进行 json_encode。数组的“订单项”部分是我无法弄清楚的部分,因为需要根据订单中的 SKU 数量(即 1、2、3 等)动态创建结构。
下面是我需要创建的数组的动态部分的示例。
$product_list_example_array =
array (
'items' => array (
0 =>
array (
'quantity' => 1,
'sku' => 'sample string 2',
'description' => 'sample string 3',
'price' => 4,
),
1 =>
array (
'quantity' => 1,
'sku' => 'sample string 2',
'description' => 'sample string 3',
'price' => 4,
),
),
);
为此,我创建了变量 $product_list,它根据产品数量为我提供了完美格式化的数组。当我回显 $product_list 时,它看起来与上面的示例完全一样,都在一行中。
所以我认为会很好用......但是,当我将 $product_list 放入更大的数组中,然后使用 json_encode 将该数组转换为 json 时,瞧,我的 $product_list 变量并没有兑换。最终json中出现的$product_list还是数组格式!
foreach( $order_item as $product ) {
$product_name = $product['name'];
$product_qty = $product['qty'];
$product_id = $product['product_id'];
$product_price = $product['line_total'];
$product_sku = get_post_meta( $product_id, '_sku', true);
$prodct_list_name[] = '['. $items_number++ .']=> array (\'quantity\' => '. $product_qty .',\'sku\' => '. $product_sku .',\'description\' => '. $product_name .'\'price\' => '. $product_price .')';
}
$product_list = implode( ',', $prodct_list_name );
echo $product_list;
$args = array (
'apiKey' => $API_KEY,
'booking' =>
array (
//this is the part of the array where I insert my $product_list array object
'items' =>
array ( $product_list
),
'pickupDetail' =>
array (
'address' => $Pickup_Address,
),
'dropoffDetail' =>
array (
'name' => $Shipping_Name,
'phone' => $Phone_Number,
'email' => $Shipping_Email,
'description' => $Order_Notes,
'address' => $Shipping_Address,
),
),
);
//display the json
$json_data = json_encode($args);
echo $json_data;
最后 json 如下所示。请查看 json 并查看除 $product_list 部分之外的整个数组是如何正确编码的。如果有办法解决这个问题或完全不同,我真的很高兴。
{"apiKey":API_KEY,"booking":{"items":["[0]=> array ('quantity' => 1,'sku' => CAN-BR,'description' => Candle | Black Raspberry'price' => 0),[1]=> array ('quantity' => 1,'sku' => ,'description' => Candle | Fig & Melon'price' => 21.95),"],"pickupDetail":{"address":"Pickup Address"},"dropoffDetail":{"name":"Cusomter Name","phone":"5555555555","email":"test@email.com","description":"Order Notes (order_comments)","address":"Delivery Address"}}}
【问题讨论】: