循环 PHP 嵌套数组 - 将值提取到 Blade 视图中 (Laravel)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24299204/
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
Looping PHP Nested Arrays - Extract values into Blade Views (Laravel)
提问by Pete
I know there are many questions on this topic, but none quite deal with this (as far as I could see).
我知道关于这个主题有很多问题,但没有一个完全解决这个问题(据我所知)。
I have a PHP array (which FYI, is returned via Guzzle response) in a Laravel Project.
我在 Laravel 项目中有一个 PHP 数组(仅供参考,通过 Guzzle 响应返回)。
The PHP array
PHP 数组
$users = array(2) {
["error"]=>
bool(false)
["spirits"]=>
array(2) {
[0]=>
array(2) {
["id"]=>
string(1) "1"
["name"]=>
string(5) "Foo"
}
[1]=>
array(2) {
["id"]=>
string(1) "2"
["name"]=>
string(3) "Bar"
}
}
}
I simply want to extract the "id" and "name" keys below, to use in a view but I'm a little stumped. I've tried the suggestions below, but can't quite work it out.
我只是想提取下面的“id”和“name”键,以便在视图中使用,但我有点困惑。我已经尝试了下面的建议,但不能完全解决。
How to Flatten a Multidimensional Array?
PHP foreach with Nested Array?
I've also looked into array_walk_recursive.
我还研究了array_walk_recursive。
Any help would be awesome and appreciated! I want to be able to use these 2 keys in Laravel like so:
任何帮助都会很棒和赞赏!我希望能够像这样在 Laravel 中使用这两个键:
Controller
控制器
return View::make('users')->with('users',$users);
View
看法
@foreach ($users as $key => $user)
{{ $user["id"] }}
{{ $user["name"] }}
@endforeach
采纳答案by The Alpha
You may try this:
你可以试试这个:
@foreach ($users['spirits'] as $user)
{{ $user["id"] }}
{{ $user["name"] }}
@endforeach
It's better to check the returned result in your controller before you send it to the view using something like this so there will be no errors in your view:
最好先检查控制器中返回的结果,然后再使用类似的方法将其发送到视图,这样视图中就不会出现错误:
$users = 'Get it from somewhere...';
if(!$users['error']) {
return View::make('users')->with('users', $users);
}
else {
// Show an error with a different view
}
回答by Chris
in case your users are always stored in the spirits
-key of your $users
variable you simply could modify your @foreach
-loop as follow:
如果您的用户始终存储在变量的spirits
-key 中,您$users
只需@foreach
按如下方式修改-loop:
@foreach ($users['spirits'] as $user)
{{ $user['id'] }}
{{ $user['name'] }}
@endforeach
Otherwise you could edit your return value from the controller. That means you simply could change the line:
否则,您可以从控制器编辑您的返回值。这意味着您只需更改行:
return View::make('users')->with('users',$users);
return View::make('users')->with('users',$users);
to
到
return View::make('users')->with('users',$users['spirits']);
return View::make('users')->with('users',$users['spirits']);
In this case you don't have access to your error
-key.
在这种情况下,您无权访问您的error
-key。