我努力让我的头衔变得有意义哈哈。我有这个JSON:
[{
"0": {
"id": 130427,
"created_at": 1512521776301,
"updated_at": 1512549188911,
"category": 0,
"platform": 6,
"date": 1513987200000,
"region": 8,
"y": 2017,
"m": 12,
"human": "2017-Dec-23",
"game": 76663
},
"2": {
"id": 131795,
"created_at": 1514172411633,
"updated_at": 1514190849639,
"category": 0,
"platform": 39,
"date": 1513987200000,
"region": 8,
"y": 2017,
"m": 12,
"human": "2017-Dec-23",
"game": 78658
}
}]
正如您所看到的,全局json中JSON对象的 位置 充当对象的名称,我不想这样做。这就是我想要的:
[{
"id": 130427,
"created_at": 1512521776301,
"updated_at": 1512549188911,
"category": 0,
"platform": 6,
"date": 1513987200000,
"region": 8,
"y": 2017,
"m": 12,
"human": "2017-Dec-23",
"game": 76663
},
{
"id": 131795,
"created_at": 1514172411633,
"updated_at": 1514190849639,
"category": 0,
"platform": 39,
"date": 1513987200000,
"region": 8,
"y": 2017,
"m": 12,
"human": "2017-Dec-23",
"game": 78658
}
]
我想要没有名字的物品。这是我正在使用的代码:
$json = file_get_contents('./releases.json');
$data = json_decode($json, TRUE);
$region = isset($_GET['region']) ? $_GET['region'] : null;
# if region is not null: ?region=8
if ($region) {
$region_filter = function($v) use ($region) {
// 8 == Worldwide
if ($v['region'] == $region || $v['region'] == 8) {
return true;
} else {
return false;
}
};
$data = array_filter($data['data'], $region_filter);
}
header('Content-Type: application/json');
echo json_encode(array($data)); // good
谢谢
答案 0 :(得分:1)
您需要使用array_values()
重新索引数组。
PHP的json_encode()
函数只会生成一个数组,如果所有数组键都是数字键并且没有任何间隙,例如0,1,2,3等问题是array_filter()
可以删除某些键并留下空白,这会导致json_encode()
包含您在示例中显示的键。您可以在调用array_values()
之前使用json_encode()
重新索引数组来解决此问题。
以下是一个例子:
<?php
// numeric array keys with no gaps
$a = ['a', 'b', 'c'];
echo json_encode($a);
// ["a","b","c"]
// filter out the 'b' element to introduce a gap in the keys
$a = array_filter($a, function ($v) {
return $v !== 'b';
});
echo json_encode($a);
// {"0":"a","2":"c"}
// re-index the array to remove gaps
$a = array_values($a);
echo json_encode($a);
// ["a","c"]