I have a POST Rest API that has a parameter that is called $arrProducts. The parameter should be an array. But the value that is sent to the API is not an array, but a string, with the form of an array.
Let me give an example of the string parameter that is passed:
"$arrProducts = array(array("product_id"=>'79',"qty"=>2,"options" =>array("525"=>'')),array("product_id"=>'41',"qty"=>3),"options"=>array("195"=>'')));"
This parameter even though it looks like an array is not. It is a string. So I tried to make it more like an array.
$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.
So after this I ended up with the pure array form "array(array("product_id"=>'79',"qty"=>2,"options" =>array("525"=>'')),array("product_id"=>'41',"qty"=>3),"options"=>array("195"=>'')))"
And now my question is how can I convert this string to an array?
OK listen what I did was to first change the way the data was trasmitted to the Rest API. I used json_encode. Then In my Rest API i grabbed the Data using json_decode.
Now here is the new issue I have. The format of the arrProducts is as follows. I have a problem parsing the json_decode thought.
$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" => ''
)
)
);
The problem is with the way I will parse the data using json_decode: Here is what I wrote but for some reason there is a problem in the options array.
$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++;
}
}
Can anyone see any classic error in this code? Cause it is not working for some reason. Probably due to the $options array. I think it is not formatted well.