如何从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)."";

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;

I assume that the ID is unique key for an Item and your Item::all()->where('id',$id) will return only one record. If this is true, the second loop is unnecessary.

Based on this assumption, I come to this code:

$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"

For explanation:

  1. Cast the array into a collection
  2. Use map to loop over it
  3. Find the Item by its ID
  4. Return the name and the quantity (this returns a collection)
  5. Implode the collection