0

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

1 Answer 1

0
  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);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.