简体   繁体   English

Laravel 4 foreach循环-想要显示最后一个元素

[英]Laravel 4 foreach loop - wanting to display the last element

I am currently trying to set up an edit page where an order form is populated using json_decode to decode json information that was saved when the form was created. 我目前正在尝试建立一个编辑页面,在其中使用json_decode填充订单以解码创建表单时保存的json信息。 Because the form's size can change I have to create the correct number of inputs so that all the json data will have a place to be displayed. 因为表单的大小可以更改,所以我必须创建正确数量的输入,以便所有json数据都有一个要显示的位置。 Fortunately as the inputs are numbered this should not be hard to do. 幸运的是,随着输入的编号,这应该不难做到。 Unfortunately I am not sure how to pick the last element of the json information that has been decoded. 不幸的是,我不确定如何选择已解码的json信息的最后一个元素。 Currently I am using: 目前,我正在使用:

public function getEdit($id){
        $order = Order::where('id', '=', $id);

        if($order->count()) {
            $order                      = $order->first();
            $order->order_serialized    = json_decode($order->order_serialized);

            foreach($order->order_serialized as $key => $value){
                $order->$key = $value;
            }
            return View::make('orders.edit')
                    ->with('order', $order);
        }   else {
            return App::abort(404);
        }
    }

to decode the information and it is working splendidly but I need to be able to pick up the last element to be able to find the total number of inputs and am not sure how I could do this without disturbing the foreach loop. 解码信息,它工作出色,但是我需要能够拾取最后一个元素才能找到输入的总数,并且不确定如何在不影响foreach循环的情况下做到这一点。 Any and all help would be greatly appreciated!! 任何和所有帮助将不胜感激! Thank you so much! 非常感谢!

You can use the count and toArray methods to find the last item. 您可以使用counttoArray方法查找最后一项。

$nItem = $order->count();
$aOrder = $order->toArray();
$aLastItem = $aOrder[$nItem-1];

集合具有last()函数以补充first()函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM