dongyan6235 2017-12-12 17:06
浏览 99
已采纳

如何从JSON中提取数据 - Laravel和JSON

This is how my json looks like ["Chicken",{"quantity":"1"},"Froggies",{"quantity":"2"},"Fryies",{"quantity":"3"}].

Is there a way that i can get the data out the results like

Chicken : 1, Froggies:2, Fryies:3

I tried to use implode to get this done but i get an error saying array to string conversion,

Below is my code

 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)."";
  • 写回答

2条回答 默认 最新

  • dtvjl64442 2017-12-12 17:42
    关注

    Maybe array of objects would be more useful in that situation, which you could get this way:

    $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条)

报告相同问题?