array_unique函数之后的数组作为JSON响应中的对象返回 [英] Array after array_unique function is returned as an object in JSON response

查看:144
本文介绍了array_unique函数之后的数组作为JSON响应中的对象返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

im尝试合并两个数组,并省略重复的值,并使用Slim框架将其作为JSON返回.我执行以下代码,但结果得到JSON的unique属性作为对象-而不是数组.我不知道为什么会这样,所以我想避免这种情况.我该怎么办?

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?

我的代码:

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

我得到的JSON响应:

An as a JSON response I get:

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

array_unique似乎返回了一些奇怪的东西,但这是什么原因?

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

推荐答案

array_unique从数组中删除重复的值,但保留数组键.

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

所以像这样的数组:

array(1,2,2,3)

将被过滤为此

array(1,2,3)

但是值"3"将保留其键"3",因此结果数组的确是

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

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

并且json_encode无法将这些值编码为JSON数组,因为键不是从零开始的.能够还原该数组的唯一通用方法是为其使用JSON对象.

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.

如果要始终发出JSON数组,则必须重新编号数组键.一种方法是将数组与一个空数组合并:

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

另一种实现方法是让array_values为您创建一个新的连续索引数组:

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

这篇关于array_unique函数之后的数组作为JSON响应中的对象返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆