dongxianshuai8927
2016-01-16 18:10
浏览 71
已采纳

PHP:将逗号分隔值对字符串转换为Array

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.

图片转代码服务由CSDN问答提供 功能建议

我有逗号分隔的值对,我想将它转换为php中的关联数组。 \ n

示例:

  {
年龄:30,
重量:80,
高度:180 
} 
  <  / pre> 
 
 

转换为:

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

我的值不在引号中,这会有所不同吗? 我的意思是: 重量:80 Vs 重量:'80'

PS 我是通过手机发布的,所以我没有太多东西 可用的花哨标记使这个问题看起来更具代表性。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douhuanbai6729 2016-01-16 18:14
    已采纳

    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);
    
    打赏 评论
  • dongzhan5246 2016-01-16 21:01

    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.
    打赏 评论

相关推荐 更多相似问题