从带有标题的数组值转换为Json格式到laravel视图

时间:2016-04-28 17:50:03

标签: json laravel

这是我的Laravel Controller索引方法:

if(count($least) == 0)
        {
            $events = DB::table('bookings')
             ->join('events','bookings.event_id','=','events.id')
             ->join(DB::raw('(select S.event_id, sum(S.spaces) as sum_spaces from spots S group by S.event_id) d'), function($join)
             {
                $join->on('bookings.event_id', '=', 'd.event_id');
             })
             ->select('bookings.event_id','events.name', 'd.sum_spaces',
                      DB::raw('COUNT(bookings.event_id) as tb'))
             ->groupBy('bookings.event_id')
             ->get();
        //return $events;

            $occupacy = array();
            $eventname_occupacy = array();

            $least = array();
            foreach($events as $event)
            {
                $occupacy[] = $event->tb / $event->sum_spaces * 100;
                $eventname_occupacy[] = $event->name;

            }   
            $least[0] =  min($occupacy);
            $least[1] =  min($eventname_occupacy);
            }
 }

在这个方法中,我得到$ less数组,其中第一个值将是百分比,第二个值是事件的标题。 我需要在转换为Json格式时为两个数组索引添加自定义标题。 我尝试过很多东西:Json_encode,response() - > json()等,但是无法获得我需要的格式。 这就是我在数组中的含义:

[2.7397260273973,"Reflexology Massage"]

这就是我想要的:

{ "least": 
    {  
       "occupacy" : "2.7397..."
       "event_name" : "Reflexology Massage"
    }
}

这样我就可以在Laravel视图中访问

$least->event_name and $least->occupacy

或者我甚至不介意在Laravel中访问数组值,如:

$array[0]  // Where this is the occupacy
$array[1]  // and this is event name

无论如何都要工作,除非我有我需要的值。

1 个答案:

答案 0 :(得分:0)

首先将名称添加到数组中的值,然后转换为json,如下所示:

$a = [2.7397260273973,"Reflexology Massage"];
$array['least'] = [
    'occupancy' => $a[0],
    'event_name' => $a[1]
];
$array = json_encode($array);

$array最后应该喜欢你的json形式。因此,您可以像对象一样访问它:$array->least->occupancy

或者,如果你只想这样访问:$least->occupancy你可以这样做:

$least = [2.7397260273973,"Reflexology Massage"];
$array = [
    'occupancy' => $least[0],
    'event_name' => $least[1]
];
$least = json_encode($array);