Laravel刀片在嵌套时非常好@foreach循环崩溃

时间:2018-02-09 22:41:33

标签: php laravel loops foreach

我不明白为什么嵌套循环如果单独运行就会抛出Trying to get property of non-object错误。代码是相同的(除了嵌套),底层数据对象不会改变,并且它们不会相互引用。

这有效:

@extends('layouts.app')

@section('title','welcome')

@section('content')

<h1 align=center>INVESTMENTS</h1>
<table align=center border=1>
<tr>
    <th>Quantity</th>
    <th>Value</th>
    <th>Unit Price</th>
</tr>
@foreach ($investment_accounts as $investment_account)
        <tr><th><h2>{{$investment_account->investment_institution_name}}</h2></th><th></th><th></th></tr>
@endforeach

@foreach ($investment_item as $investment_item)

        <tr><th><h4 align=center><b>{{$investment_item->investment_name}}</b></br></h4></th><th></th><th></th></tr>
        <tr>
        <td>Quantity: {{$investment_item->investment_quantity}}</br> </td>
        <td>Fair Market Value: ${{number_format($investment_item->investment_sale_price_fmv,2)}}</br> </td>
        <td>Unit cost: ${{number_format(floatval($investment_item->investment_sale_price_fmv)/intval($investment_item->investment_quantity),2)}}</td>
        </tr>
        <hr>

@endforeach

@endsection

但是这个炸弹:

@extends('layouts.app')

@section('title','welcome')

@section('content')

<h1 align=center>INVESTMENTS</h1>
<table align=center border=1>
<tr>
    <th>Quantity</th>
    <th>Value</th>
    <th>Unit Price</th>
</tr>
@foreach ($investment_accounts as $investment_account)
        <tr><th><h2>{{$investment_account->investment_institution_name}}</h2></th><th></th><th></th></tr>

    @foreach ($investment_item as $investment_item)

            <tr><th><h4 align=center><b>{{$investment_item->investment_name}}</b></br></h4></th><th></th><th></th></tr>
            <tr>
            <td>Quantity: {{$investment_item->investment_quantity}}</br> </td>
            <td>Fair Market Value: ${{number_format($investment_item->investment_sale_price_fmv,2)}}</br> </td>
            <td>Unit cost: ${{number_format(floatval($investment_item->investment_sale_price_fmv)/intval($investment_item->investment_quantity),2)}}</td>
            </tr>
            <hr>

    @endforeach

@endforeach

@endsection

我正在使用XAMPP / PHP7在Laravel 5.5中工作 有什么想法吗?

2 个答案:

答案 0 :(得分:0)

嵌套循环并不是一个好习惯。它产生不良结果,因为在内循环完成一个圆之前,外循环类完成执行。最好的方法是在循环外声明一个函数,在函数中运行第二个循环。最后从第一个循环调用函数,即

function myFunction(){
    for(u in someObject){
        // doing something
    }
}

for(x in someObject){
    myFunction();
}

上面的方法总能产生更好的结果。虽然在C编程中,在使用多维数组时循环内部循环很常见!对我来说这很糟糕。

答案 1 :(得分:0)

你的内循环问题是你已经将两个变量命名为相同:

// incorrect
@foreach ($investment_item as $investment_item)

// correct
@foreach ($investment_items as $investment_item)

您的第一个示例有效,因为它只循环一次。使用嵌套循环,$investment_item仍然在第一个循环中作用域,因此崩溃。