我在试着合并一些麻烦事。我试过these answers,但我认为它们不符合我的需要。
我有两个(或更多)这样的人
{
item: {
icon: "http://services.runescape.com/m=itemdb_rs/4922_obj_sprite.gif?id=2",
icon_large: "http://services.runescape.com/m=itemdb_rs/4922_obj_big.gif?id=2",
id: 2,
type: "Default",
typeIcon: "http://www.runescape.com/img/categories/Default",
name: "Cannonball",
description: "Ammo for the Dwarf Cannon.",
current: {
trend: "neutral",
price: 208
},
today: {
trend: "positive",
price: "+8"
},
members: "true",
day30: {
trend: "positive",
change: "+8.0%"
},
day90: {
trend: "negative",
change: "-4.0%"
},
day180: {
trend: "positive",
change: "+9.0%"
}
}
}我该怎么把它们加到这样的东西上呢?
{
items: [
{
icon: "http://services.runescape.com/m=itemdb_rs/4922_obj_sprite.gif?id=2",
icon_large: "http://services.runescape.com/m=itemdb_rs/4922_obj_big.gif?id=2",
id: 2,
type: "Default",
typeIcon: "http://www.runescape.com/img/categories/Default",
name: "Cannonball",
description: "Ammo for the Dwarf Cannon.",
//Same other stuff here
},
{
icon: "http://services.runescape.com/m=itemdb_rs/4922_obj_sprite.gif?id=2",
icon_large: "http://services.runescape.com/m=itemdb_rs/4922_obj_big.gif?id=2",
id: 2,
type: "Default",
typeIcon: "http://www.runescape.com/img/categories/Default",
name: "Cannonball",
description: "Ammo for the Dwarf Cannon.",
//Same other stuff here
}
]
}发布于 2015-08-22 19:57:36
首先,初始的JSON字符串无效,键没有用双引号括起来,所以我们需要修复这个问题。
使用初始字符串重复10次的示例代码
<?php
$string = file_get_contents('sample.json');
//var_dump($string);
$data = jsonDecode($string);
for ($i=0;$i<=10;$i++)
$list['items'][] = $data['item'];
print json_encode($list);
function jsonDecode($string, $assoc=true, $fixNames=true){
if(strpos($string, '(') === 0){
$string = substr($string, 1, strlen($string) - 2); // remove outer ( and )
}
if($fixNames){
$string = preg_replace("/(?<!\"|'|\w)([a-zA-Z0-9_]+?)(?!\"|'|\w)\s?:/", "\"$1\":", $string);
}
return json_decode($string, $assoc);
}json的修复功能是从这里提取的,https://stackoverflow.com/a/17748840/5043552。
输出按要求进行。
发布于 2015-08-22 20:04:37
我不知道每个json结构是从哪里来的,但我假设它是可以迭代的:
$finalArray = array();
foreach ($jsonStructs as $json)
{
$j = json_decode($json, true);
$finalArray['items'][] = $j['item'];
}
$finalJson = json_encode( $finalArray);我使用每个json结构并将其解码为php数组。然后,我从它获取项值,并将其放置到另一个数组中,该数组将容纳每个数组。
最后,我将最终数组编码为json,这将为您提供所需的内容。
https://stackoverflow.com/questions/32160013
复制相似问题