我有一个 POST Rest API,它有一个名为 $arrProducts 的参数。参数应该是一个数组。但是发送给 API 的值不是数组,而是字符串,具有数组的形式。
让我举一个传递的字符串参数的例子:
"$arrProducts = array(array("product_id"=>'79',"qty"=>2,"options" =>array("525"=>'')),array("product_id"=>'41',"qty"=>3),"options"=>array("195"=>'')));"
这个参数即使看起来像一个数组也不是。它是一个字符串。所以我试着让它更像一个数组。
$stringVar = $_POST['arrProducts'];
$str = rtrim($stringVar, ";"); //To lose the semicolon at the end of the string
$arrProducts = substr($str, 15); // To lose the first part of the string "$arrProducts = " to make it formatted exactly like an array.
所以在这之后我得到了纯数组形式"array(array("product_id"=>'79',"qty"=>2,"options" =>array("525"=>'')),array("product_id"=>'41',"qty"=>3),"options"=>array("195"=>'')))"
现在我的问题是如何将此字符串转换为数组?
好的,听我做的是首先更改数据传输到 Rest API 的方式。我使用了 json_encode。然后在我的 Rest API 中,我使用 json_decode 抓取了数据。
现在这是我遇到的新问题。arrProducts 的格式如下。我在解析 json_decode 思想时遇到问题。
$product_id = "45";
$qty = 20;
$option_type_id_for_option_id_151 = '826';
$option_type_id_for_option_id_124 = '657,658,';
$option_type_id_for_option_id_126 = 'Test for field option';
$arrProducts = array(
array(
"product_id" => $product_id,
"qty" => $qty,
"options" => array(
"151" => $option_type_id_for_option_id_151,
"124" => $option_type_id_for_option_id_124,
'126' => $option_type_id_for_option_id_126
)
),
array(
"product_id" => '60',
"qty" => '1',
"options" => array(
"156" => '862',
"167" => '899',
"168" => '902',
"159" => '877',
"160" => '889,890,891,'
)
),
array(
"product_id" => '58',
"qty" => '1',
"options" => array(
"174" => '938',
"176" => '943',
"178" => ''
)
)
);
问题在于我将使用 json_decode 解析数据的方式:这是我写的,但由于某种原因,选项数组中存在问题。
$stringVar = $_POST['arrProducts'];
$arrProductsVar = json_decode($stringVar, TRUE);
$i = 0;
$arrProducts = array();
if ($arrProductsVar !== NULL)
{
foreach ($arrProductsVar['arrProducts'] as $arrProduct){
$options = array();
foreach($arrProduct['options'] as $key => $val){
$options[$key] = $val;
}
$arrProducts[$i] = array('product_id' => $arrProduct['product_id'],'qty' => $arrProduct['qty'], 'options' => $options);
$i++;
}
}
任何人都可以在此代码中看到任何经典错误吗?因为它由于某种原因无法正常工作。可能是由于 $options 数组。我认为它的格式不正确。