1

I have comma separated value pairs and I would like to convert it to associative array in php.

Example:

{ 
   Age:30,
   Weight:80,
   Height:180
}

Converted to:

Echo $obj['Weight']; // 80

Does it make a difference that my values are not in inverted commas? I mean: Weight:80 Vs Weight:'80'

P.S. I've posted from a phone, so I don't have a lot of fancy markup available to make this question look more presentable.

Marci-man
  • 2,113
  • 3
  • 28
  • 76
  • 2
    Possible duplicate of [json\_decode to array](http://stackoverflow.com/questions/5164404/json-decode-to-array) – Sean Jan 16 '16 at 18:26
  • Looks like the OP is asking if the values need to be within tick marks. Seems like a yes or no question. – AnthonyW Jan 16 '16 at 20:57

2 Answers2

3

http://php.net/manual/en/function.json-decode.php It's an JSON object which you would like to convert to an array.

$string = '{ "Age":30, "Weight":80, "Height":180 }';

$array = json_decode($string, true);
echo $array['Age']; // returns 30

Provided that the given string is a valid JSON.

UPDATE

If that doesn't work because the string doesn't contain a valid JSON object (because I see the keys are missing double quotes), you could execute this regex function first:

$string = "{ Age:30, Weight:80, Height:180 }";
$json = preg_replace('/(?<!")(?<!\w)(\w+)(?!")(?!\w)/u', '"$1"', $string); // fix missing quotes

$obj = json_decode($json, true);
echo $obj['Age']; // returns 30

When using the regex above, make sure the string doesn't contain any quotes at all. So make sure that not some keys have quotes and some not. If so, first get rid of all quotes before executing the regex:

str_replace('"', "", $string);
str_replace("'", "", $string);
Community
  • 1
  • 1
Erik van de Ven
  • 4,747
  • 6
  • 38
  • 80
  • OP doesn't have valid JSON and there is no contradiction or any indications that OP has valid JSON. *"Assuming OP already has an array he would just have to use $obj['Age']"* <- Assumptions doesn't help – Rizier123 Jan 16 '16 at 18:28
  • Thanks for your answer. I tried your solution and it didn't work. I dug a bit deeper and I found out that don't really have real string. It seems like a zero based array of characters. Could this be the reason why json_decode not working for me? Or all strings are arrays of chars in PHP? – Marci-man Jan 16 '16 at 18:47
  • Well if it's truly a zero based array of characters, you could try imploding them first: `$string = implode($array);`, and then you could transform the json to an array with the appropriate keys using my above mentioned code. And no, strings are not arrays of chars in PHP, it's not like C. Well you could echo a single character by echo'ing something like `$string[0]`, but that aside, if you could echo the complete string, it's just a string and not an array. – Erik van de Ven Jan 16 '16 at 19:02
  • I've tried the implode() but it doesn't work either! I just get NULL from json_decode(). Is it because of lack of quotes on my value strings. – Marci-man Jan 16 '16 at 19:09
  • Maybe you should post some more details of your code. According to the documentation http://php.net/manual/en/function.json-decode.php you should give the function a string as argument. And NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit. – Erik van de Ven Jan 16 '16 at 19:09
  • Arighty, that solved it. The thing with missing quotations was not going down well with json_decode(). I used your regular expression to place quotations and now it works! Thank you so much! – Marci-man Jan 16 '16 at 22:07
  • I just have a follow-up question about the regular expression. I have values like:: "weight":"80.5" and the RE is turning this into:: "weight":"80"."5" I'm horrible with RE, could you please help? – Marci-man Jan 16 '16 at 23:35
  • Here you go: `$json = preg_replace('/(?<!")(?<!\w)([\w.]+)(?!")(?!\w)/u', '"$1"', $string);` I've placed the \w between square brackets and added a dot (.), that should work. – Erik van de Ven Jan 17 '16 at 13:30
1

You can get all values in an array by using this basic example:

// your string
$string = "{ 
   Age:30,
   Weight:80,
   Height:180
}";

// preg_match inside the {}
preg_match('/\K[^{]*(?=})/', $string, $matches);

$matchedResult = $matches[0];
$exploded = explode(",",$matchedResult); // explode with ,

$yourData = array();
foreach ($exploded as $value) {
    $result = explode(':',$value); // explode with :
    $yourData[$result[0]] = $result[1];
}

echo "<pre>";
print_r($yourData);

Result:

Array
(
    [Age] => 30
    [Weight] => 80
    [Height] => 180
)

Explanation:

  1. (?<=}) look behind asserts.
  2. K[^{] matches the opening braces and K tells what was matched.
devpro
  • 16,184
  • 3
  • 27
  • 38