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

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.

  • 写回答

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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示