PHP: Convert comma separated value pair string to Array

后端 未结 2 1237
悲&欢浪女
悲&欢浪女 2021-01-25 09:17

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
}
         


        
2条回答
  •  既然无缘
    2021-01-25 09:41

    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('/(?

    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);
    

提交回复
热议问题