laravel 在laravel控制器中创建数据数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49398942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 17:53:09  来源:igfitidea点击:

Creating Array of data in laravel controller

arrayslaravelarraylist

提问by Ronald Torres

$document = new Document();
$document->title = $request['title'];
$document->description = $request['description'];

When i try to output the above code using echo $document;i get this result:

当我尝试使用输出上述代码时,echo $document;我得到以下结果:

{"title":"asdfasdf","description":"asdfasdfsadf"}

What i want is to create my own array of data and output the same format. This is the code i am trying to experiment but it does not work:

我想要的是创建我自己的数据数组并输出相同的格式。这是我尝试尝试的代码,但它不起作用:

    $data = array(
      "title" => "hello",
      "description" => "test test test"
    );

    echo $data;

Any Help would be appreciated. Thanks.

任何帮助,将不胜感激。谢谢。

回答by Eazy Sam

All collections also serve as iterators, allowing you to loop over them as if they were simple PHP arrays:

所有集合也用作迭代器,允许您循环遍历它们,就像它们是简单的 PHP 数组一样:

foreach ($document as $data) {
    echo $data->title;
    echo $data->description;
}

There is no difference while using a PHP framework. You may refer the official PHP Arrays Manualpage to work with the language construct.

使用 PHP 框架时没有区别。您可以参考官方PHP 数组手册页面来使用语言结构。

If you need to convert JSON to array, use:

如果您需要将 JSON 转换为数组,请使用:

$data->toArray();

$data->toArray();

OR

或者

json_decode($data);

json_decode($data);

Here is your code:

这是你的代码:

$data = array(
  "title" => "hello",
  "description" => "test test test"
);

// may also declare

// 也可以声明

$data = ["title" => "hello", "description" => "test test test"];

Use:

用:

var_dump($data);

var_dump($data);

OR

或者

print_r($data);

打印_r($数据);

// and the output will be

// 输出将是

["title" => "hello", "description" => "test test test",]