简体   繁体   中英

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM