I am trying to recurse through a multidimensional Object/Array structure to create JSON, but the following isn't working. $data is reset, but I'm not sure how to prevent this.
public function encodeJSON($data) {
foreach ($data as $key => $value) {
if (is_array($value) || is_object($value)) {
$json->$key = $this->encodeJSON($value);
} else {
$json->$key = $value;
}
}
return json_encode($json);
}
$datais not reset. It produces one string with all of the values including nested arrays. I tested it on several arrays.{"foo":"{\"bar\":\"baz\"}"}instead of the intended{"foo":{"bar":"baz"}}. You need to encode the whole object/array at once.json_encode($data);? json_encode() is perfectly capable of serializing arrays and objects!