简体   繁体   中英

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.

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. 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

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

After that I can convert the merged array into 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:

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 )

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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