Php Laravel按键获取数组元素

Php Laravel按键获取数组元素,php,arrays,laravel,Php,Arrays,Laravel,我有一个对象数组。实体用户有两个字段:firstName和lastName; 在我的控制器中,我将所有用户添加到称为employees的some数组中 $employees = array(); foreach($users as $user) { $employees[] = $user->firstName; } 如何通过firstName获取数组的view元素 我试着这样做: return View::make('nameOfFile')->with('employe

我有一个对象数组。实体用户有两个字段:firstName和lastName; 在我的控制器中,我将所有用户添加到称为employees的some数组中

$employees = array();
foreach($users as $user) {
    $employees[] = $user->firstName;
}
如何通过firstName获取数组的view元素

我试着这样做:

return View::make('nameOfFile')->with('employees', $employees);
array(
  [0] => "John",
  [1] => "Martha",
  ...
)
$employees['John']
但它不起作用


提前感谢

您这样做只是将字符串附加到数组中。数组的键将是从0开始的整数

要获取用户名作为索引,请将
$employees
数组的键设置为
$user->firstName
,然后在该位置存储
$user
的对象。以下是修复代码:

$employees = array();
foreach($users as $user) {
    $employees[$user->firstName] = $user;
}
在此之后,您应该能够执行
$employees['John']

请记住,要在视图中使用数组,必须将数组传递给视图。前任: 在控制器方法中,您应该具有如下内容:

return View::make('nameOfFile')->with('employees', $employees);
array(
  [0] => "John",
  [1] => "Martha",
  ...
)

将名称添加到数组中时,会出现如下情况:

return View::make('nameOfFile')->with('employees', $employees);
array(
  [0] => "John",
  [1] => "Martha",
  ...
)
您需要通过索引访问名称,我不建议在索引中包含名称,如果两个用户具有相同的名称怎么办?最终将覆盖阵列中的一个:

Array("John", "John", "Martha")
在使用键作为名称的数组后,您将得到:

Array(
 [John] => someUser, // <- here you lost one John.
 [Martha] => SomeUser,
)
数组(
[John]=>someUser,//someUser,
)

您将附加到普通数组,这意味着数组键将自动从零开始按递增顺序为整数。假设我们在
$users
数组中有“Alice”和“Bob”,那么您的代码将生成一个
$employees
数组,该数组包含两个元素:
$employees[Ø]=“Alice”
$employees[1]=“Bob”

要获得想要的结果,您需要使用
$user->firstName
值作为键:

$employees = array();
foreach ($users as $user) {
    $employees[$user->FirstName] = $user->firstName;
}
虽然这不是很有用,但我认为你真正想得到的是:

$employees = array();
foreach ($users as $user) {
    // use the whole object for this user, not only the firstName field
    $employees[$user->FirstName] = $user;
}

我们可以看到$users数组吗?请同时查看$employers数组