这就是我的json看起来像["Chicken",{"quantity":"1"},"Froggies",{"quantity":"2"},"Fryies",{"quantity":"3"}].
有没有办法可以将数据输出结果,如
Chicken : 1
,Froggies:2
,Fryies:3
我尝试使用implode来完成此操作但我收到错误array to string conversion
,
以下是我的代码
foreach($request->get('item_id') as $key => $id)
{
$selected_item = Item::all()->where('id',$id);
foreach($selected_food as $select)
{
$food_selected[]= $select->name ;
$food_selected[] = ['quantity' => $request->get('quantity')[$key]];
}
}
$query ="Your items are ".implode(',',$food_selected)."";
答案 0 :(得分:0)
在这种情况下,对象阵列可能会更有用,你可以这样做:
$arr = [];
foreach ( $request->get('item_id') as $key => $id ) {
$selected_item = Item::all()->where('id', $id);
foreach ( $selected_item as $select ) {// $selected_item or $selected_food here
/*
$obj = new stdClass;
$obj->{$select->name} = $request->get('quantity')[$key];
$arr[] = $obj;*/
$arr[$select->name] = (int) $request->get('quantity')[$key];
}
}
$query = '';
foreach ( $arr as $k => $v ) {
$query .= ' '.$k.': '.$v.',';
}
$query = rtrim($query, ',');
$query = ltrim($query);
$query = "Your items are ".$query;
答案 1 :(得分:0)
我认为ID是Item的唯一键,而Item::all()->where('id',$id)
只返回一条记录。如果是这样,则不需要第二个循环。
基于这个假设,我来到这个代码:
$result = collect($request->get('item_id'))
->map(function($itemId, $itemKey) use ($request) {
$item = Item::find($itemId);
return $item->name . ' : ' . $request->get('quantity')[$itemKey];
})->implode(',');
// $result contains the string: "Chicken : 2, Fries : 1"
解释: