0

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

5
  • 1
    What have you tried so far and what specific issues are you getting? Commented Jun 18, 2019 at 7:59
  • I try to remove the string from it. tried json_decodes. but i could not solve Commented Jun 18, 2019 at 8:00
  • 1
    This is invalid json as it says in php doc (Example #3 common mistakes using json_decode()). Can you ask those who send a request change the message format? Commented Jun 18, 2019 at 8:08
  • @marv255 I cannot request them That is what I am getting. Commented Jun 18, 2019 at 8:09
  • @user1687891 maybe this could help you. But I don't recommend to use regexp for json, only if you a 100% sure. Commented Jun 18, 2019 at 8:13

3 Answers 3

2

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
)
Sign up to request clarification or add additional context in comments.

2 Comments

If a comma in the original data was problematic, then I don’t see how that comma replaced by a & 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 know this can be cause new problems hence the So to just add to the confusion
1

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"
}*/

https://3v4l.org/naIJE

Comments

0

Your json isn't well formatted. Try this:

$param = '{"year":2019,"month":5,"id":3}';
var_dump(json_decode($param, true));

2 Comments

yes if data is like that, then its easy. but in my case what shall I do .
Then you can try with explode() to get what you need and write that array yourself

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.