Tomk07
Tomk07

Reputation: 113

Laravel - Blade; How to cycle through nested json objects with different top level titles, in a @foreach loop

Most languages let you cycle through a json object, getting the top level names.

object = {
    "a": {"inner json objects"},
    "b" : {"..."},
    "C" : {"..."}
}

For example in html.twig the syntax is as such:

{% for title, section  in object %}
  // do something with title (ie. a, b, c)
  // do something (cycle through) with section(ie. '...')
{% endfor %}

I want to do the equivalent in blade.php.

I have tried multiple variations on the blade syntax, such as

@foreach(json_encode($object) as $title) 

but I can't figure it out, and I can't find any appropriate documentation online. This stackoverflow question is the closest I could find., but it isn't quite appropriate as it doesn't stipulate the object I'm grabbing from

Any help would be appreciated.

Upvotes: 1

Views: 668

Answers (2)

lagbox
lagbox

Reputation: 50561

You are probably just looking for the foreach syntax that allows you to define the key name as well:

foreach ($something as $key => $value)

Everything inside the (...) in the Blade @foreach(...) directive is just regular PHP, by the way.

Upvotes: 2

Logan C
Logan C

Reputation: 36

Two arrays in foreach loop

This should answer your question. You'll need to combine them since PHP foreach loops only loop one array at a time.

You could do a nested loop as well if that works for your needs.

Upvotes: 0

Related Questions