我希望将返回的数据格式化如下:
{
"cols": [
{
"label":"Topping",
"type":"string"
},
{
"label":"Slices",
"type":"number"
}
],
"rows": [
{
"c":[
{"v":"Mushrooms"},
{"v":3}
]
},
{
"c":[
{"v":"Onions"},
{"v":1}
]
},
{
"c":[
{"v":"Olives"},
{"v":1}
]
},
{
"c":[
{"v":"Zucchini"},
{"v":1}
]
},
{
"c":[
{"v":"Pepperoni"},
{"v":2}
]
}
]
}
在Laravel有没有办法做到这一点?
答案 0 :(得分:0)
我假设你的db:
/*
Table: label_type
Column: label type
Topping string
Slices number
Table: Some_Food
Column: name quantity
Mushrooms 3
Onions 1
Olives 1
Zucchini 1
Pepperoni 2
*/
$label_type = DB::table('label_type')->get();
$cols = array();
foreach($label_type as $item1)
{
$arr = array([
'label'=>$item1->label,
'type' =>$item1->type
]);
$cols = array_merge_recursive($cols, $arr);
}
$foods = DB::table('Some_Food')->get();
$rows = array();
foreach($foods as $item2)
{
$arr1 = array(['v'=>$item2->name]);
$arr2 = array(['v'=>$item2->quantity]);
$c = array_merge_recursive($arr1,$arr2);
$mage = array(['c'=>$c]);
$rows = array_merge_recursive($rows, $mage);
}
$result = array(['cols'=>$cols,'rows'=>$rows]);
echo dd($result);
或者你只是测试,查看我的代码(Laravel 5):
$label = array('Topping','Slices');
$type = array('string','number');
$cols = array();
for ($i=0;$i<2;$i++)
{
$arr = array([
'label'=>$label[$i],
'type' =>$type[$i]
]);
$cols = array_merge_recursive($cols, $arr);
}
$name = array('Mushrooms','Onions','Olives','Zucchini','Pepperoni');
$quantity = array(3,1,1,1,2);
$rows = array();
for ($i=0;$i<5;$i++)
{
$arr1 = array(['v'=>$name[$i]]);
$arr2 = array(['v'=>$quantity[$i]]);
$c = array_merge_recursive($arr1,$arr2);
$mage = array(['c'=>$c]);
$rows = array_merge_recursive($rows, $mage);
}
$result = array(['cols'=>$cols,'rows'=>$rows]);
echo dd($result);