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.

2
  • 3
    Possible duplicate of json_decode to array Commented Jan 16, 2016 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. Commented Jan 16, 2016 at 20:57

2 Answers 2

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

8 Comments

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
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?
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.
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.
Maybe you should post some more details of your code. According to the documentation 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.
|
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.