skip to Main Content

I want to display randomly in json_decode foreach. These codes are for Laravel/php.

my table:

id    url        attr
1     post-1     [{"at1":"Attr-A1","at2":"Attr-A2",.....}]

my array (attr):

[{
"at1":"Attr-A1",
"at2":"Attr-A2",
"at3":"Attr-A3",
"at4":"Attr-A4",
},
{
"at1":"Attr-B1",
"at2":"Attr-B2",
"at3":"Attr-B3",
"at4":"Attr-B4",
},
{
"at1":"Attr-C1",
"at2":"Attr-C2",
"at3":"Attr-C3",
"at4":"Attr-C4",
}]

my controller:

$post = Post::where('url',$url)->first();

my blade

@foreach ( json_decode($post->attr, true) as $arr )
    <p>{{ $arr['at1'] }}</p> ,
    <p>{{ $arr['at2'] }}</p> ,
    <p>{{ $arr['at3'] }}</p> ,
    <p>{{ $arr['at4'] }}</p>
    <br>
@endforeach

Qutput: I want the output to show randomly.

Attr-A1 , Attr-A2 , Attr-A3 , Attr-A4
Attr-C1 , Attr-C2 , Attr-C3 , Attr-C4
Attr-B1 , Attr-B4 , Attr-B3 , Attr-B4

or

Attr-C1 , Attr-C2 , Attr-C3 , Attr-C4
Attr-A1 , Attr-A2 , Attr-A3 , Attr-A4
Attr-B1 , Attr-B4 , Attr-B3 , Attr-B4

shuffle or array_random : These two do not work for me.

Does json_decode display randomly?

2

Answers


  1. shuffle() works, you might have been using it in the wrong way.
    First in your Controller shuffle($post);
    Then in your blade

    @foreach ($post as $lists)
        <p>
        @foreach ($lists as $list) 
            {{$list.', '}}
        @endforeach
        </p>
    @endforeach
    
    Login or Signup to reply.
  2. You could use call_user_func to shuffle the json_decode result inside the foreach statement:

    @foreach (call_user_func(function ($arr) { shuffle($arr); return $arr; }, json_decode($post->attr, true)) as $arr)
        <p>{{ $arr['at1'] }}</p> ,
        <p>{{ $arr['at2'] }}</p> ,
        <p>{{ $arr['at3'] }}</p> ,
        <p>{{ $arr['at4'] }}</p>
        <br>
    @endforeach
    

    PHP demo on 3v4l.org

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search