【问题标题】:Laravel get element of array by keyLaravel 按键获取数组元素
【发布时间】:2014-08-14 16:08:26
【问题描述】:

我有一组对象用户。 Entity User 有两个字段:firstName 和 lastName; 在我的控制器中,我将所有用户添加到称为员工的某个数组中。

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

如何通过 firstName 获取数组的视图元素。

我试过这样:

$employees['John'] 但它不起作用

提前致谢

【问题讨论】:

  • 我们可以看看 $users 数组,也请一个 $employers

标签: php arrays laravel


【解决方案1】:

你这样做的方式只是将一个字符串附加到一个数组中。数组的键是从 0 开始的整数。

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

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

之后你应该可以$employees['John']

请记住,为了能够在视图中使用数组,您必须将数组传递给视图。前任: 在你的控制器方法中,你应该有这样的东西:

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

【讨论】:

    【解决方案2】:

    当您将名称添加到数组中时,您将得到如下内容:

    array(
      [0] => "John",
      [1] => "Martha",
      ...
    )
    

    您需要通过索引访问名称,我不建议在索引中使用名称,如果两个用户具有相同的名称怎么办?你最终会覆盖数组中的一个:

    Array("John", "John", "Martha")
    

    拥有一个以键为名称的数组后,您最终会得到:

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

    【讨论】:

      【解决方案3】:

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

      要获得您想要的结果,您需要使用 $user-&gt;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;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-10-25
        • 2021-12-16
        • 1970-01-01
        • 1970-01-01
        • 2020-11-02
        • 2017-02-27
        • 2011-01-17
        相关资源
        最近更新 更多