【问题标题】:Array datatype convertion in Laravel v5.4 PHPLaravel v5.4 PHP中的数组数据类型转换
【发布时间】:2017-09-07 11:20:51
【问题描述】:

控制器。

namespace App\Http\Controllers;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class TestDBController extends Controller
{
    public function index()
    {
        $db_ext = \DB::connection('extdb');
        $customer = $db_ext->table('customer')->get();
        var_dump($customer);
        // var_dump($customer);
        return view('customers.index', ['customer' => $customer]);
    }
}

查看

<table class="table table-responsive" id="kunder-table">
    <thead>
        <th>ID</th>
        <th>name</th>
        <th>Email</th>
        <th>Mobil</th>
        <th>Address</th>
        <th>Address2</th>
        <th>Address3</th>
    </thead>
    <tbody>
    @foreach($customer as $customer)
        <tr>
            <td>{!! $customer->customerid !!}</td>
            <td>{!! $customer->name !!}</td>
            <td>{!! $customer->email !!}</td>
            <td>{!! $customer->mobile !!}</td>
            <td>{!! $customer->adress1 !!}</td>
            <td>{!! $customer->adress2 !!}</td>
            <td>{!! $customer->adress3 !!}</td>
        </tr>
    @endforeach
    </tbody>
</table>

这是“var_dump”结果。

    object(Illuminate\Support\Collection)[261]
          protected 'items' => 
            array (size=365)
              0 => 
                object(stdClass)[262]
                  public 'BANKACCOUNT' => string '' (length=0)
                  public 'CUSTOMERID' => int 10000
                  ...

我得到的最终结果是 “未定义的属性:stdClass::$customerid。 但是每个表字段中也有customerid。 那么我怎样才能得到正确的列表视图呢?谢谢。

【问题讨论】:

  • 你可能需要 $customer->id
  • 你使用的是什么版本的 Laravel?
  • 尝试用 customerid 替换 CUSTOMERID
  • 'CUSTOMERID' 和其他在这种情况下区分大小写因此将$customer-&gt;customerid 更正为$customer-&gt;CUSTOMERID
  • @Ross 这是 5.4 版。

标签: php laravel type-conversion


【解决方案1】:

请尝试以下更改:

TestDBController

return view('customers.index', ['customers' => $customer]);

查看文件

@foreach($customers as $customer)
        <tr>
            <td>{!! $customer->customerid !!}</td>
            <td>{!! $customer->navn !!}</td>
            <td>{!! $customer->email !!}</td>
            <td>{!! $customer->mobile !!}</td>
            <td>{!! $customer->adress1 !!}</td>
            <td>{!! $customer->adress2 !!}</td>
            <td>{!! $customer->adress3 !!}</td>
        </tr>
    @endforeach

在您的控制器部分,您正在传递customer 变量中的值,并且在foreach 循环的视图中您使用相同的名称。

foreach循环的默认语法是:

foreach($array as $values)

根据您的代码,您使用的变量与您的集合数组相同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多