我正在开发一个Wordpress
站点,允许用户订购特定产品的x
数量。我使用cookie
传递网站周围订单的数据。
最初一切都很好,当我调用print_r($orderArray)
时,包含订单项的array
将显示。
然而,我的代码不再工作,由于某种原因$orderArray
不再是array
。下面的代码将输出NOT ARRAY
function process_order_form_handler() {
if(isset($_COOKIE['order_cookie'])){
json_encode($_COOKIE['order_cookie']);
$orderArray = json_decode($_COOKIE['order_cookie'], true);
echo $orderArray;
$orderTime = date('Y-m-d-H-i-s');
$orderContent = "Order Request Code: " . $orderTime . "<br/>";
$orderContent .= "===Order===" . "<br/>";
//Loop through the Array and print data
if(is_array($orderArray)){
foreach($orderArray as $item){
if(!array_key_exists('comment', $item)){
$orderContent .= "Stock Code: " . $item['stockCode'] . " Qty: " . $item['quantity'] . "<br/>";
}else{
$orderContent .= "Comments: " . $item['comment'];
}
}
}else{
echo "NOT ARRAY";
}
}
}
我不知道为什么,我所做的唯一改变是通过修改我的form action
到permalink
的帖子,然后我检查POST
数组是否存在,如果它存在,我调用functions-process-order.php
中包含的方法,当我遇到问题时。
有人知道为什么$orderArray
不被视为array
吗?
var_dump($orderArray)
结果
string '[{"stockCode":"CBL202659/A","quantity":"3"},{"stockCode":"CBL201764","quantity":6},{"comment":"","quantity":null},{"comment":""},{"comment":""},{"comment":""},{"comment":"vdcvcvcv"},{"comment":""}]' (length=237)
print_r($_COOKIE['order_cookie']);
结果
[{"stockCode":"CBL202659/A","quantity":"3"},{"stockCode":"CBL201764","quantity":6}]
您正在编码但未分配给任何变量,并试图解码,更改:
json_encode($_COOKIE['order_cookie']);
$orderArray = json_decode($_COOKIE['order_cookie'], true);
...
$encoded = json_encode($_COOKIE['order_cookie']);
$orderArray = json_decode($encoded, true);
echo json_last_error_msg(); //check if any error
...