繁体   English   中英

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

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

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

例:

{ 
   Age:30,
   Weight:80,
   Height:180
}

转换成:

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

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

PS我是从手机上张贴的,所以我没有很多花哨的标记可以使这个问题看起来更像样。

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

前提是给定的字符串是有效的JSON。

更新

如果由于字符串不包含有效的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

使用上面的正则表达式时,请确保该字符串根本不包含任何引号。 因此,请确保没有某些键带有引号,而有些则没有。 如果是这样,在执行正则表达式之前,请先除去所有引号:

str_replace('"', "", $string);
str_replace("'", "", $string);

您可以使用以下基本示例获取数组中的所有值:

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

结果:

Array
(
    [Age] => 30
    [Weight] => 80
    [Height] => 180
)

说明:

  1. (?<=})后面的断言。
  2. K[^{]匹配大括号,K告诉匹配的内容。

暂无
暂无

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

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