PHP-在Wordpress/Woocommerce中为JSON包添加多个数组



我正试图使用PHP构建一个JSON包,但格式有问题。

这是我想要的格式:

{
"SenderSuburb": "xxxx",
"SenderState": "xxx",
"SenderPostcode": "xxx",
"ReceiverSuburb": "xxx",
"ReceiverState": "xxx",
"ReceiverPostcode": "xxx",
"CustomerName": "xxx",
"CustomerCode": "xx",
"Rows": [{
"QtyDecimal": 1,
"Weight": 100,
"Length": 0.5,
"Width": 0.3,
"Height": 0.2,
"Description": "Carton"
}],
"Rows": [{
"QtyDecimal": 1,
"Weight": 100,
"Length": 0.5,
"Width": 0.3,
"Height": 0.2,
"Description": "Carton"
}]
}

目前,它正在打印正确的JSON格式,但当涉及到添加多行时,它只添加一行,而不是多行。

我尝试了array_push,但没能让它发挥作用。

这是我的代码:

$thearray = array();
$thearray[SenderSuburb] = "xxx";
$thearray[SenderState] = "xxx";
$thearray[SenderPostcode] = "xxx";
$thearray[ReceiverSuburb] = "xxx";
$thearray[ReceiverState] = "xxx";
$thearray[ReceiverPostcode] = "xxx";
$thearray[CustomerName] = "xxx";
$thearray[CustomerCode] = "xxx";
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {

$item_name = $cart_item['data']->get_title();
$item_weight = $cart_item['data']->get_weight();
$item_height = $cart_item['data']->get_height();
$item_width = $cart_item['data']->get_width();
$item_length = $cart_item['data']->get_length();

$thearray[Rows] = array([
'QtyDecimal' => '1', 
'Weight' => $item_weight,
'Length' => $item_length,
'Width' => $item_width,
'Height' => $item_height,
'Description' => $item_name
]);

}

print("<pre>".print_r($thearray,true)."</pre>");
$entire_array_JSON = json_encode($thearray);
echo $entire_array_JSON;

这是输出:

Array
(
[SenderSuburb] => xxxx
[SenderState] => xxx
[SenderPostcode] => xxx
[ReceiverSuburb] => xxxx
[ReceiverState] => xxx
[ReceiverPostcode] => xxx
[CustomerName] => xxxx
[CustomerCode] => xxxx
[Rows] => Array
(
[0] => Array
(
[QtyDecimal] => 1
[Weight] => 8
[Length] => 60
[Width] => 40
[Height] => 2
[Description] => xxxxx
)
)
)

以及解码的JSON响应:

{
"SenderSuburb": "xxxx",
"SenderState": "xxx",
"SenderPostcode": "xxx",
"ReceiverSuburb": "xxx",
"ReceiverState": "xxx",
"ReceiverPostcode": "xxx",
"CustomerName": "xxx",
"CustomerCode": "xxx",
"Rows": [{
"QtyDecimal": "1",
"Weight": "8",
"Length": "60",
"Width": "40",
"Height": "2",
"Description": "xxxx"
}]
}

正如您所看到的,它只显示一行,而不是多行,尤其是当购物车中有多个产品时。

如有任何帮助,我们将不胜感激。

已解决。由于PHP不允许重复的键,所以我只能分配一个键,并使用array_push向该键添加多个值。

$thearray[Rows]=array((;