【问题标题】:Laravel 4 weird first result in the foreach loopLaravel 4 奇怪的第一个结果是 foreach 循环
【发布时间】:2015-01-05 15:13:21
【问题描述】:

这是我在控制器中的 getIndex() 函数中的内容

public function getIndex() {

    $categories = Category::all();

    foreach ($categories as $category) {
        $categories[$category->id] = $category->name;
    }
......
}

所以我希望从循环中获取所有类别名称。

但是,例如,如果我想通过在视图中执行此操作来获得结果

        @foreach ($categories as $name) 
            <ul>
                <li>{{var_dump($name)}}</li>
            </ul>
        @endforeach

结果是这样的

  • object(Category)#169 (20) { ["fillable":protected]=> array(1) { [0]=> string(4) "name" } ["connection":protected] => NULL ["table":protected]=> NULL ["primaryKey":protected]=> string(2) "id" ["perPage":protected]=> int(15) ["incrementing"]=> bool (true) ["timestamps"]=> bool(true) ["attributes":protected]=> array(4) { ["id"]=> string(1) "1" ["name"]=> string (3) "foo1" ["created_at"]=> 字符串(19) "2014-11-08 14:29:30" ["updated_at"]=> 字符串(19) "2014-11-08 14:29: 30" } ["original":protected]=> array(4) { ["id"]=> string(1) "1" ["name"]=> string(3) "foo1" ["created_at"] => 字符串(19) "2014-11-08 14:29:30" ["updated_at"]=> 字符串(19) "2014-11-08 14:29:30" } ["relations":protected]= > array(0) { } ["隐藏":protected]=> array(0) { } ["visible":protected]=> array(0) { } ["appends":protected]=> array(0) { } ["guarded":protected]=> array(1) { [0]=> string(1) "*" } ["dates":protected]=> array(0) { } ["touches":protected ]=> array(0) { } ["observables":protected]=> array(0) { } ["with":p rotected]=> array(0) { } ["morphClass":protected]=> NULL ["exists"]=> bool(true) }

  • string(3) "foo1"

  • 字符串(11)“foo2”

第一个结果来自哪里,我该如何摆脱它?谢谢!

【问题讨论】:

    标签: php laravel laravel-4


    【解决方案1】:

    第一个项目保留在第一个 $categories 数组中。它的id 字段的值为1,但数组中的键当然为零。不存在具有零 id 的项目,因此不会被覆盖。

    最好这样写:

    public function getIndex() {
    
        $categoryList = Category::all();
    
        foreach ($categoryList as $oCategory) {
            $categories[$oCategory->id] = $oCategory->name;
        }
    
        // ......
    }
    

    或者简单地说:

        foreach (Category::getAll as $category) {
            $categories[$category->id] = $category->name;
        }
    

    【讨论】:

      【解决方案2】:

      你可以试试这个:

      // Get an associative array
      $categories = Category::lists('name', 'id');
      

      然后将它传递给视图做循环:

      <ul>
          @foreach ($categories as $id => $name) 
              <li>{{$name}}</li>
          @endforeach
      </ul>
      

      【讨论】:

      • offtopic: alpha,我有一个关于 laravel 自动加载的问题。我写了这个问题,但不允许发布引用lack of quality.... 这是一个理论问题,所以我有点理解。你能告诉我在哪里可以问你吗?可能在您的博客中或其他地方?
      • @itachi,当然,你可能会问,可能使用我的博客联系页面或我的电子邮件,如果可能的话,我会尽力回答:-)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-09
      • 2017-05-19
      • 2016-05-26
      相关资源
      最近更新 更多