doufu8887 2014-08-14 07:44
浏览 60

Laravel按键获取数组元素

I have array of objects users. Entity User has two fields: firstName and lastName; In my controller I add all users to the some array which called employees.

$employees = array();
foreach($users as $user) {
    $employees[] = $user->firstName;
}

How can i get on the view element of array by firstName.

I tried like this:

$employees['John'] but it doesn't work

Thanks in advance

  • 写回答

3条回答 默认 最新

  • dongsu3664 2014-08-14 07:48
    关注

    The way that you are doing it you are just appending a string to an array. The keys of the array will be integers starting from 0.

    To get the user first name as the index, set the Key of the $employees array to be the $user->firstName, then in that position store the object of the $user. Here is the code fixed:

    $employees = array();
    foreach($users as $user) {
        $employees[$user->firstName] = $user;
    }
    

    After that you should be able to do $employees['John'].

    Remember that to be able to use the array in the View you must pass the array to the view. Ex: In your controller method you should have something like this:

    return View::make('nameOfFile')->with('employees', $employees);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。