简体   繁体   English

将数组从控制器传递到Laravel中的视图

[英]Passing array from controller to view in Laravel

I am new to Laravel and trying to pass a one dimensional array from controller to the view. 我是Laravel的新手并试图将一维数组从控制器传递给视图。

This is my controller function 这是我的控制器功能

 public function onedim_array()
    {
        $info = array(
            'firstname' => 'John',
            'lastname' => 'Cena',
            'from' => 'USA'
            );

        return view('one_dim_array',  compact('info'));
    }

This is my view file: 这是我的查看文件:

<?php

foreach($info as $i)
{
    echo $i['firstname'];
}

?>

It gives me the following error: 它给了我以下错误:

ErrorException in 34a7177cfbceee0b4760125499bdaca34b567c0b.php line 5: Illegal string offset 'firstname' (View: C:\\AppServ\\www\\blog4\\resources\\views\\one_dim_array.blade.php) 34a7177cfbceee0b4760125499bdaca34b567c0b.php中的ErrorException第5行:非法字符串偏移'firstname'(查看:C:\\ AppServ \\ www \\ blog4 \\ resources \\ views \\ one_dim_array.blade.php)

I don't know where I am making mistake. 我不知道我在哪里弄错了。 Please Help 请帮忙

由于它不是多维数组,因此使用this而不是foreach()

$info['firstname']

foreach() allow you to traverse all items in your array. foreach()允许您遍历数组中的所有项目。 And in your code snippet 并在您的代码段中

<?php

foreach($info as $i)
{
    echo $i['firstname'];
}

?>

you try to get element with index 'firstname' from a string (in your example it will be 'John' ). 你试图从一个字符串中获取索引'firstname'元素(在你的例子中它将是'John' )。 If you want traverse all elements and display them, try this: 如果要遍历所有元素并显示它们,请尝试以下操作:

foreach($info as $i)
{
    echo $i;
}

or if you want to display specific element of your array, try this 或者如果要显示数组的特定元素,请尝试此操作

echo $info['firstname'];

or 要么

echo $info['lastname'];

I think you're expecting to accept multidimensional array to the view. 我认为你期望接受视图的多维数组。 I think here's the value of the array you're expecting to pass to the view 我想这是你期望传递给视图的数组的值

Controller code: 控制器代码:

public function onedim_array()
{
    $info = array(
        array(
            'firstname' => 'John',
            'lastname' => 'Cena',
            'from' => 'USA'
        ),
        array(
            'firstname' => 'John',
            'lastname' => 'Doe',
            'from' => 'Canada'
        ),
    );

    return view('one_dim_array',  compact('info'));
}

PS. PS。 Suggestion before diving to study a framework: "Master the basics of PHP first", and learn how to debug. 潜水之前建议研究框架:“先掌握PHP的基础知识”,并学习如何调试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM