im trying to merge two arrays with omitting duplicated values and return it as a JSON with Slim framework. I do following code, but in result I get unique
property of a JSON as object - not as an array. I don't know why does it happen, and I'd like to avoid it. How can I do it?
My code:
$galleries = array_map(function($element){return $element->path;}, $galleries);
$folders = array_filter(glob('../galleries/*'), 'is_dir');
function transformElems($elem){
return substr($elem,3);
}
$folders = array_map("transformElems", $folders);
$merged = array_merge($galleries,$folders);
$unique = array_unique($merged);
$response = array(
'folders' => $dirs,
'galleries' => $galleries,
'merged' => $merged,
'unique' => $unique);
echo json_encode($response);
An as a JSON response I get:
{
folders: [] //array
galleries: [] //array
merged: [] //array
unique: {} //object but should be an array
}
It seems that array_unique
returns something strange, but what's the reason?
array_unique
removes values from the array that are duplicates, but the array keys are preserved.So an array like this:
will get filtered to be this
but the value "3" will keep his key of "3", so the resulting array really is
And
json_encode
is not able to encode these values into a JSON array because the keys are not starting from zero without holes. The only generic way to be able to restore that array is to use a JSON object for it.If you want to always emit a JSON array, you have to renumber the array keys. One way would be to merge the array with an empty one:
Another way to accomplish that would be letting array_values create a new consecutively-indexed array for you: