我试图合并一些jsons。我试过these answers,但我认为它们不适合我的需要。
我有2个(或更多)这些jsons
{
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
}
]
}
答案 0 :(得分:2)
首先,初始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
输出是按要求的
答案 1 :(得分:1)
我不知道每个json结构的来源,但我认为它将是可以迭代的东西:
$finalArray = array();
foreach ($jsonStructs as $json)
{
$j = json_decode($json, true);
$finalArray['items'][] = $j['item'];
}
$finalJson = json_encode( $finalArray);
我将每个json结构解码为php数组。然后我从中获取项目值并将其放入另一个将保存每个值的数组中。
最后,我将finally数组编码为json,它将为您提供所要求的内容。