循环PHP嵌套数组-将值提取到Blade视图中(Laravel) [英] Looping PHP Nested Arrays - Extract values into Blade Views (Laravel)

查看:311
本文介绍了循环PHP嵌套数组-将值提取到Blade视图中(Laravel)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有关此主题的问题很多,但据我所知,没有一个问题能解决这个问题.

I know there are many questions on this topic, but none quite deal with this (as far as I could see).

我在Laravel项目中有一个PHP数组(FYI,通过Guzzle响应返回).

I have a PHP array (which FYI, is returned via Guzzle response) in a Laravel Project.

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"
    }
  }
}

我只是想提取下面的"id"和"name"键,以在视图中使用,但是我有些困惑.我尝试了以下建议,但无法完全解决.

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.

如何展平多维数组?

带有嵌套数组的PHP foreach吗?

我还研究了 array_walk_recursive .

任何帮助都会令人敬畏和赞赏!我希望能够像这样在Laravel中使用这两个键:

Any help would be awesome and appreciated! I want to be able to use these 2 keys in Laravel like so:

控制器

return View::make('users')->with('users',$users);

查看

 @foreach ($users as $key => $user)
     {{ $user["id"] }}
     {{ $user["name"] }}
 @endforeach

推荐答案

您可以尝试以下方法:

@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
}

这篇关于循环PHP嵌套数组-将值提取到Blade视图中(Laravel)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆