简体   繁体   English

将带值的逗号分隔字符串转换为嵌套数组

[英]Convert comma separated string with value to nested array

I am receiving csv data as separate strings which I am trying to convert into nested arrays, and then json.我收到 csv 数据作为单独的字符串,我试图将其转换为嵌套的 arrays,然后是 json。

The strings I am receiving are like this, where the last element is the value.我收到的字符串是这样的,最后一个元素是值。

$str1 = "name,firstname,Bob";
$str2 = "name,lastname,Dylan";

Here I need to convert the strings into nested arrays which would be equivalent to the arrays below.在这里,我需要将字符串转换为嵌套的 arrays,这相当于下面的 arrays。 This is the bit I am struggling with.这是我正在努力的一点。

$arr1 = ["name" => ["firstname" => "Bob"]];
$arr2 = ["name" => ["lastname" => "Dylan"]];

I can then use a array_merge_recursive to combine them然后我可以使用 array_merge_recursive 来组合它们

$merged = array_merge_recursive($arr1, $arr2);

After that I can convert the merged array into json之后我可以将合并的数组转换为 json

  1. Pass in your dynamic number of strings to a loop.将动态数量的字符串传递给循环。

  2. Parse the comma-separated values.解析逗号分隔值。

  3. Use the values to push data into your array structure.使用这些值将数据推送到数组结构中。

Code: ( Demo )代码:(演示

$strings = ["name,firstname,Bob", "name,lastname,Dylan"];
$result = [];
foreach ($strings as $csv) {
    [$level1, $level2, $value] = str_getcsv($csv);
    $result[$level1][$level2] = $value;
}
var_export($result);

Output: Output:

array (
  'name' => 
  array (
    'firstname' => 'Bob',
    'lastname' => 'Dylan',
  ),
)

Or more succinctly, you can push directly from the array destructuring step to achieve the same result as above: ( Demo )或者更简洁地说,您可以直接从数组解构步骤推送以获得与上述相同的结果:( Demo

$result = [];
foreach ($strings as $csv) {
    [$level1, $level2, $result[$level1][$level2]] = str_getcsv($csv);
}
var_export($result);

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

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