解析带有 key=value 声明的字符串并创建一个关联数组[重复]

问题描述 投票:0回答:3

如何分解以下字符串:

$str = "ProductId=123, Name=Ancient Roots, Modern Pursuits, Country=India, City=Bangalore, Price=3368"

这样输出数组将包含:

[
    "ProductId" => "123",
    "Name" => "Ancient Roots, Modern Pursuits",
    "Country" => "India",
    "City" => "Bangalore",
    "Price" => "3368" 
]

我尝试用“逗号”进行爆炸,然后每个元素再次用“等于”进行爆炸。

$arr = explode(",", $str);

再一次

$prodarr = explode("=", $arr[0]);  
$product["ProductId"] = $prodarr[1]

但是当名称中存在另一个逗号时,我遇到了问题

Ancient Roots, Modern Pursuits

php associative-array text-parsing
3个回答
4
投票

你的结构非常脆弱,不易断裂。但你仍然可以尝试解析它。

首先在

=
爆炸。您将获得下一个键和当前值。

然后循环这些并在

,
上爆炸,并选择下一个键的最后一个元素和所有先前的部分作为值(sample):

<?php
$str = "ProductId=123, Name=Ancient Roots, Modern Pursuits, Country=India, City=Bangalore, Price=3368";

$chunks = explode('=', $str);
$keys = [];
$values = [];

foreach ($chunks as $i => $chunk) {
    $parts = explode(',', $chunk);

    if ($i != count($chunks) - 1) {
        $keys[] = trim(array_pop($parts));
    }

    if ($i != 0) {
        $values[] = implode(',', $parts);
    }
}

var_dump(array_combine($keys, $values));

1
投票

我玩了一下。我使用 preg_match_all() 来提取包含 no 和 no = 后跟 a = 的字符,后跟 no = 后跟 , 或行尾的字符的模式。这是结果:

$result = array();
preg_match_all('/([^=,]+=[^=]+)(,|$)/', $string, $matches);
foreach($matches[1] as $data){
 $data = explode('=', $data);
 $result[trim($data[0])] = trim($data[1]);
}
$result = json_encode($result);

结果是:

{"ProductId":"123","Name":"Ancient Roots, Modern Pursuits","Country":"India","City":"Bangalore"}

0
投票

尝试这样的事情

<?php
    $str = "ProductId=123, Name=Ancient Roots, Modern Pursuits, Country=India, City=Bangalore, Price=3368";
    $str_arr = explode(",", $str);
    $json_array = array();

for ($i = 0; $i < sizeof($str_arr); $i++)
    {
    if (isset($str_arr[$i + 1]))
        {
        if (strpos($str_arr[$i + 1], '=') !== false)
            {
            $prod = explode("=", $str_arr[$i]);
            $json_array["" . $prod[0] . ""] = "" . $prod[1] . "";
            }
          else
            {
            $textAppend = "," . $str_arr[$i + 1];
            $prod = explode("=", $str_arr[$i]);
            $json_array["" . $prod[0] . ""] = "" . $prod[1] . "" . $textAppend . "";
            $i++;
            }
        }
      else
        {
        $prod = explode("=", $str_arr[$i]);
        $json_array["" . $prod[0] . ""] = "" . $prod[1] . "";
        }
    }


var_dump($json_array);
?>
© www.soinside.com 2019 - 2024. All rights reserved.