What are the best practices for iterating over multidimensional arrays in PHP to generate JSON data?
When iterating over multidimensional arrays in PHP to generate JSON data, it is best to use recursive functions to handle nested arrays. This allows you to traverse each level of the array and convert it to JSON format. By recursively iterating over the array elements, you can ensure that all nested arrays are properly processed and included in the final JSON output.
function convertArrayToJson($array) {
$json = [];
foreach ($array as $key => $value) {
if (is_array($value)) {
$json[$key] = convertArrayToJson($value);
} else {
$json[$key] = $value;
}
}
return $json;
}
$array = [
'key1' => 'value1',
'key2' => [
'key3' => 'value3',
'key4' => 'value4'
]
];
$jsonData = json_encode(convertArrayToJson($array));
echo $jsonData;