In current versions of concrete5, the JSON helper can be used to convert JSON to an object or to an array. But that was not always the case. Before concrete5.6.2 the JSON helper could only convert a JSON string into an object. But what if you need to use the data in an array?
The solution is a small recursive function.
function object_to_array($data) {
if(is_array($data) || is_object($data)){
$result = array();
foreach($data as $key => $value){
$result[$key] = $this->object_to_array($value);
}
return $result;
}
return $data;
}
To use it, first get the JSON string as an object, then convert it to a php array.
$json = Loader::helper('json');
$json_as_object = $json->decode($json_string);
$json_as_array = object_to_array($json_as_object);
The JSON library used within the concrete5 JSON helper actually has an option that translates a JSON string to an array directly. Before concrete5.6.2 that option was not available through the helper. However a pull request on GitHub included a fix for this and is available in concrete5 core from concrete5.6.2+.
To take advantage of the additional functionality of concrete5.6.2 we can use some adaptive code that will do whatever is needed for the interface concrete5 provides.
$json_as_array = $json->decode($json_string, true);
if (is_object($json_as_array)){
$json_as_array = object_to_array($json_as_array);
}
Here the extra parameter 'true' is used to request an array return. On an up-to-date concrete5 system, we get an array. On an older core, the extra parameter is ignored and we instead get an object. So we test for an object and then use the conversion routine to change it back to an array.
In practice, function object_to_array() will either be in the same class as the calling code or in a library class, so you will need to call it through the containing object class.
$array_data = $this->object_to_array($object_data);
or
$array_data = $whatever->object_to_array($object_data);