PHP: Convert comma separated value pair string to Array -
i have comma separated value pairs , convert associative array in php.
example:
{ age:30, weight:80, height:180 }
converted to:
echo $obj['weight']; // 80
does make difference values not in inverted commas? mean: weight:80 vs weight:'80'
p.s. i've posted phone, don't have lot of fancy markup available make question more presentable.
http://php.net/manual/en/function.json-decode.php it's json object convert array.
$string = '{ "age":30, "weight":80, "height":180 }'; $array = json_decode($string, true); echo $array['age']; // returns 30
provided given string valid json.
update
if doesn't work because string doesn't contain valid json object (because see keys missing double quotes), execute 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 regex above, make sure string doesn't contain quotes @ all. make sure not keys have quotes , not. if so, first rid of quotes before executing regex:
str_replace('"', "", $string); str_replace("'", "", $string);
Comments
Post a Comment