Laravel 4奇怪的第一个结果是foreach循环

时间:2014-11-09 03:47:26

标签: php laravel laravel-4

这是我的控制器中的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

结果就像

  • 对象(类别)#169(20){[&#34; fillable&#34;:protected] =&gt; array(1){[0] =&gt; string(4)&#34; name&#34; } [&#34; connection&#34;:protected] =&gt; NULL [&#34; table&#34;:protected] =&gt; NULL [&#34; primaryKey&#34;:protected] =&gt; string(2)&#34; id&#34; [&#34; perPage&#34;:保护] =&GT; int(15)[&#34;递增&#34;] =&gt; bool(true)[&#34; timestamps&#34;] =&gt; bool(true)[&#34; attributes&#34;:protected] =&gt; array(4){[&#34; id&#34;] =&gt;字符串(1)&#34; 1&#34; [&#34;名称&#34;] =&GT; string(3)&#34; foo1&#34; [&#34; created_at&#34;] =&GT; string(19)&#34; 2014-11-08 14:29:30&#34; [&#34;的updated_at&#34;] =&GT; string(19)&#34; 2014-11-08 14:29:30&#34; } [&#34; original&#34;:protected] =&gt; array(4){[&#34; id&#34;] =&gt;字符串(1)&#34; 1&#34; [&#34;名称&#34;] =&GT; string(3)&#34; foo1&#34; [&#34; created_at&#34;] =&GT; string(19)&#34; 2014-11-08 14:29:30&#34; [&#34;的updated_at&#34;] =&GT; string(19)&#34; 2014-11-08 14:29:30&#34; } [&#34; relations&#34;:protected] =&gt; array(0){} [&#34; hidden&#34;:protected] =&gt; array(0){} [&#34; visible&#34;:protected] =&gt; array(0){} [&#34;追加&#34;:protected] =&gt; array(0){} [&#34; guarded&#34;:protected] =&gt; array(1){[0] =&gt; string(1)&#34; *&#34; } [&#34;日期&#34;:受保护] =&gt; array(0){} [&#34; touches&#34;:protected] =&gt; array(0){} [&#34; observables&#34;:protected] =&gt; array(0){} [&#34; with&#34;:protected] =&gt; array(0){} [&#34; morphClass&#34;:protected] =&gt; NULL [&#34;存在&#34;] =&gt; bool(true)}

  • string(3)&#34; foo1&#34;

  • string(11)&#34; foo2&#34;

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

2 个答案:

答案 0 :(得分:2)

你可以试试这个:

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

然后将其传递给视图执行循环:

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

答案 1 :(得分:0)

第一个项目保留在第一个$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;
    }