我遇到了将数据库查询中的变量传递给视图的问题。变量本身传递正常,我可以var_dump它来查看数组的内容。问题是当我尝试调用数组的一部分时,我得到一个未定义的索引错误。
控制器:
public function displayCustomer()
{
$id = $_GET['id'];
$user = DB::table('customers')->where('id', '=', $id)->get();
return View::make('single')->withuser($user);
}
查看
<body>
<?php
if (Auth::check() != TRUE)
{
return Redirect::guest('login')->with('failed', 'Login Failed');
}
?>
<?php
//var_dump($user);
echo($user['name'])
?>
</body>
到目前为止,我能够var_dump $ user数组并且它工作正常,但是,当我尝试回显数组的一部分时,我得到未定义的索引,即使我知道一个事实' name'是我的索引之一。我也试过$ user [1]并得到同样的错误。
array(1) {
[0]=> object(stdClass)#148 (11) {
["id"] => int(1)
["name"]=> string(9) "paul rudd"
["email"]=> string(18) "email@email.com"
["phone"]=> string(10) "6305555555"
["address"]=> string(15) "123 fake street"
["item"]=> string(13) "6 pcs"
["total_price"]=> float(500)
["paid_amount"]=> float(400)
["balance"]=> float(100)
["created_at"]=> string(19) "0000-00-00 00:00:00"
["updated_at"]=> string(19) "0000-00-00 00:00:00"
}
}
答案 0 :(得分:4)
根据你的var_dump输出尝试;
<?php echo $user[0]->name; ?>
您的用户是一个对象数组。在您的原始查询中,如果您专门挑选一个ID,那么获取first
结果而不是使用get
可能会更好,就像这样;
$user = DB::table('customers')->where('id', '=', $id)->first();
注意->first()
然后你就可以了;
<?php echo $user->name; ?>