Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping PHP Nested Arrays - Extract values into Blade Views (Laravel)

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.

The PHP array

$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.

How to Flatten a Multidimensional Array?

PHP foreach with Nested Array?

I've also looked into array_walk_recursive.

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

Controller

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

View

 @foreach ($users as $key => $user)
     {{ $user["id"] }}
     {{ $user["name"] }}
 @endforeach
like image 286
Pete Avatar asked Jun 19 '14 05:06

Pete


2 Answers

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
}
like image 185
The Alpha Avatar answered Nov 02 '22 09:11

The Alpha


in case your users are always stored in the spirits-key of your $users variable you simply could modify your @foreach-loop as follow:

@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);

to

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

In this case you don't have access to your error-key.

like image 29
Chris Avatar answered Nov 02 '22 09:11

Chris