简体   繁体   English

PHP:将逗号分隔的值对字符串转换为数组

[英]PHP: Convert comma separated value pair string to Array

I have comma separated value pairs and I would like to convert it to associative array in php. 我有逗号分隔的值对,我想将其转换为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' 我的意思是:重量:80 Vs重量:'80'

PS I've posted from a phone, so I don't have a lot of fancy markup available to make this question look more presentable. PS我是从手机上张贴的,所以我没有很多花哨的标记可以使这个问题看起来更像样。

http://php.net/manual/en/function.json-decode.php It's an JSON object which you would like to convert to an array. http://php.net/manual/zh-CN/function.json-decode.php这是您要转换为数组的JSON对象。

$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. 前提是给定的字符串是有效的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: 如果由于字符串不包含有效的JSON对象而导致该方法不起作用(因为我看到键缺少双引号),则可以先执行此regex函数:

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

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. K[^{]匹配大括号,K告诉匹配的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM