合并对象中的数组

时间:2014-11-12 17:00:10

标签: php json

我是php和json的新手。能告诉我如何获得我想要的输出吗?

JSON文件:

{
   "1415772360":[
     {"apple":"0"},
     {"mango":"0"},
     {"grapefruit":"0"},
     {"melons":"12"},
     {"peaches":"2"},
     {"banana":"1"}
   ],
   "1415772420":[
     {"apple":"0"},
     {"mango":"0"},
     {"grapefruit":"0"},
     {"melons":"7"},
     {"peaches":"1"},
     {"banana":"1"}
   ]
}

期望输出

[
  {
    "minute":"1415772360",
    "apple":"0",
    "mango":"0",
    "grapefruit":"0",
    "melons":"12",
    "peaches":"2",
    "banana":"1”
  },
  {
    "minute":"1415772420",
    "apple:"0",
    "mango":"0",
    "grapefruit":"0",
    "melons":"7",
    "peaches":"1",
    "banana":"1”
  }
]

我怎样才能在PHP中执行此操作? 我非常感谢你的帮助。感谢。

2 个答案:

答案 0 :(得分:7)

我会试试json_decode。它不会获得您想要的输出,但它会从您的JSON创建一个数组。

文档:http://php.net/manual/en/function.json-decode.php

我的测试:

$json = "{\"1415772360\":[{\"apple\":\"0\"},{\"mango\":\"0\"},{\"grapefruit\":\"0\"},
{\"melons\":\"12\"},{\"peaches\":\"2\"},{\"banana\":\"1\"}], \"1415772420\":
[{\"apple\":\"0\"},{\"mango\":\"0\"},{\"grapefruit\":\"0\"},{\"melons\":\"7\"},
{\"peaches\":\"1\"},{\"banana\":\"1\"}]}";

$new = json_decode($json);

print_r($new);

输出:

stdClass Object ( [1415772360] => Array ( [0] => stdClass Object ( [apple] => 0 ) 
[1] => stdClass Object ( [mango] => 0 ) [2] => stdClass Object ( [grapefruit] => 0 ) 
[3] => stdClass Object ( [melons] => 12 ) [4] => stdClass Object ( [peaches] => 2 ) 
[5] => stdClass Object ( [banana] => 1 ) ) [1415772420] => Array ( [0] => stdClass Object ( [apple] => 0 ) 
[1] => stdClass Object ( [mango] => 0 ) [2] => stdClass Object ( [grapefruit] => 0 ) 
[3] => stdClass Object ( [melons] => 7 ) [4] => stdClass Object ( [peaches] => 1 ) 
[5] => stdClass Object ( [banana] => 1 ) ) )

答案 1 :(得分:0)

tyteen4a03是正确的,这只需要一些循环来重写结构。这将按如下方式完成:

// Original JSON string
$json = '{
   "1415772360":[
     {"apple":"0"},
     {"mango":"0"},
     {"grapefruit":"0"},
     {"melons":"12"},
     {"peaches":"2"},
     {"banana":"1"}
   ],
   "1415772420":[
     {"apple":"0"},
     {"mango":"0"},
     {"grapefruit":"0"},
     {"melons":"7"},
     {"peaches":"1"},
     {"banana":"1"}
   ]
}';

// Convert JSON to array
$content = json_decode($json);

// Create new array container
$crate = array();

// Get minutes
foreach ($content AS $minute => $fruitbasket) {
  $tmp = new stdClass;
  $tmp->minutes = $minute;

  // Get array of objects
  foreach ($fruitbasket AS $fruits)
  {
    // Get object element and value
    foreach ($fruits AS $key => $value)
    {
        // add to temporary object
        $tmp->$key = $value;
    }
  }

  // write to new array
  $crate[] = $tmp;
}


print(json_encode($crate));