The array after the array_unique function is returned as an object in the JSON response

im trying to combine two arrays with omitting duplicate values ​​and return them as JSON with Slim framework. I am executing the following code, but as a result, I get the unique property of the JSON object as an object, and not as an array. I do not know why this is happening, and I would like to avoid it. How can i do this?

My code is:

 $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); 

As a JSON response, I get:

 { folders: [] //array galleries: [] //array merged: [] //array unique: {} //object but should be an array } 

http://i.imgur.com/cfHy8Od.png

Array_unique seems to return something weird, but what's the reason?

+7
php slim
source share
1 answer

array_unique removes values ​​from the array that are duplicates, but the keys of the array are preserved.

So an array like this:

 array(1,2,2,3) 

will be filtered as

 array(1,2,3) 

but the value "3" will store its key "3", so the resulting array is really

 array(0 => 1, 1 => 2, 3 => 3) 

And json_encode cannot encode these values ​​into a JSON array, because keys do not start from scratch without holes. The only general way to recover this array is to use a JSON object for it.

If you want to always generate a JSON array, you must renumber the keys of the array. One way is to combine the array with an empty one:

 $nonunique = array(1,2,2,3); $unique = array_unique($nonunique); $renumbered = array_merge($unique, array()); json_encode($renumbered); 

Another way to achieve this would be to allow array_values ​​to create a new sequentially indexed array for you:

 $nonunique = array(1,2,2,3); $renumbered = array_values(array_unique($nonunique)); json_encode($renumbered); 
+14
source share

All Articles