<?php
function flattenArray(array $array, string $prefix = "", string $seperator = "."): array {
$result = [];
foreach ($array as $key => $value) {
$key = rtrim($key, $seperator);
if (!is_array($value)) {
$result[$prefix . $key] = $value;
continue;
}
$result = array_merge($result, flattenArray($value, $prefix . $key . $seperator));
}
ksort($result);
return $result;
}
// Example
// json example from https://www.json.org/example.html
$jsonString = <<<JSON
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
}
JSON;
var_dump(flattenArray(json_decode($jsonString, true)));