[英]Restructure JSON
I now have a JSON response from the server like, but i want to restructure it, according to dates. 我现在有来自服务器的JSON响应,但我希望根据日期对其进行重组。 for eg i now have
因为我现在有
{
"items":
[
{
"A": [
{
"name": "a",
"date": "2/10/2010",
"sales": "100"
},
{
"name": "b",
"date": "6/10/2010",
"sales": "400"
}
],
"B": [
{
"name": "c",
"date": "2/10/2010",
"sales": "1000"
},
{
"name": "d",
"date": "6/10/2010",
"sales": "400"
}
]
},
{
"C": [
{
"name": "a",
"date": "10/10/2010",
"sales": "100"
},
{
"name": "b",
"date": "6/10/2010",
"sales": "100"
}
],
"D": [
{
"name": "c",
"date": "2/10/2010",
"sales": "300"
},
{
"name": "c",
"date": "2/10/2010",
"sales": "1100"
}
]
}
]
}
but now i want to restructure by dates, for a particular day need to know all the sales to have like, 但现在我想按日期进行重组,因为某一天需要知道所有的销售情况,
{
"date1" : [sales, sales, sales],
"date2" : [sales, sales],
"date3" : [sales]
}
how can this be done? 如何才能做到这一点?
I can only assume that you want this: 我只能假设你想要这个:
var arr = JSON.parse(response); // or something like that (assuming valid JSON)
// or just assign the array literal
var result = {};
for (var i=0; i<arr.length; i++) {
var date = arr[i].date,
sales = arr[i].sales;
if (date in result)
result[date].push(sales);
else
result[date] = [sales];
}
Assuming you get your JSON worked out: 假设你得到了你的JSON:
<?php
$list = array(
array(
'product' => 'a',
'date' => '2012-08-01',
'sales' => 500,
),
array(
'product' => 'b',
'date' => '2012-08-02',
'sales' => 600,
),
array(
'product' => 'c',
'date' => '2012-08-01',
'sales' => 250,
),
array(
'product' => 'd',
'date' => '2012-08-02',
'sales' => 800,
),
);
echo json_encode($list);
?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
var JSON = '<?php echo json_encode($list); ?>';
var pJson = jQuery.parseJSON(JSON);
var cArray = new Array();
for each ( i in pJson ) {
if ( typeof cArray[i.date] == 'undefined' ) {
cArray[i.date] = Array();
}
cArray[i.date].push(i.sales);
}
</script>
I added the php section to show what a JSON string should look like. 我添加了php部分来显示JSON字符串应该是什么样子。 This solution also requires jQuery.
这个解决方案还需要jQuery。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.