Reputation: 864
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
Upvotes: 0
Views: 60
Reputation: 57121
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
)
Upvotes: 2
Reputation: 23958
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"
}*/
Upvotes: 1
Reputation: 418
Your json isn't well formatted. Try this:
$param = '{"year":2019,"month":5,"id":3}';
var_dump(json_decode($param, true));
Upvotes: 0