I am getting from url value something like below:
$param = "{year:2019,month:5,id:3}"
I am not being able to convert it to array.
Can anybody please help me
I am getting from url value something like below:
$param = "{year:2019,month:5,id:3}"
I am not being able to convert it to array.
Can anybody please help me
Any time you have a string like this it is possible that values can cause problems due to containing values you don't expect (like commas or colons). So to just add to the confusion and because it was just an interesting experiment I came up with the idea of translating the string to a URL encoded string (with & and =) and then parsing it as though it was a parameter string...
parse_str(strtr($param, ["{" => "", "}" => "", ":" => "=", "," => "&"]), $params);
gives the $params array as...
Array
(
[year] => 2019
[month] => 5
[id] => 3
)
& would be any less problematic, when you try and parse the result as a query string. {year:20,19,month:5,id:3} still results in 'year' => '20' and '19' => '' here.I think that needs to be parsed manually.
First explode on comma without {} to separate each of the key value pairs then loop and explode again to separate key from values.
$param = explode(",", substr($param, 1, -1));
foreach($param as $v){
$temp = explode(":", $v);
$res[$temp[0]] = $temp[1];
}
var_dump($res);
/*
array(3) {
["year"]=>
string(4) "2019"
["month"]=>
string(1) "5"
["id"]=>
string(1) "3"
}*/
Your json isn't well formatted. Try this:
$param = '{"year":2019,"month":5,"id":3}';
var_dump(json_decode($param, true));
explode() to get what you need and write that array yourself