Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array after array_unique function is returned as an object in JSON response

Tags:

php

slim

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
}

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

It seems that array_unique returns something strange, but what's the reason?

like image 803
akn Avatar asked Aug 13 '14 21:08

akn


1 Answers

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

So an array like this:

array(1,2,2,3)

will get filtered to be this

array(1,2,3)

but the value "3" will keep his key of "3", so the resulting array really is

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

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:

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

json_encode($renumbered);

Another way to accomplish that would be letting array_values create a new consecutively-indexed array for you:

$nonunique = array(1,2,2,3);
$renumbered = array_values(array_unique($nonunique));

json_encode($renumbered);
like image 198
Sven Avatar answered Sep 29 '22 18:09

Sven