FareedR's avatar

How can I iterate imploded data with another imploded data ?

// database

// stocks 
id | name | time_frame | signal
1       test	3,5			test1,test2


//expected result 
3 : test1
    +
5 : test 2

// current result ( because idk how to iterate another imploded data ) 
test1
   +
test2

// blade
<p style="font-size:15.5px; color:black; font-weight:900;">
	{!! str_replace('+', '<br /> <span style="padding-left:10px;">+</span> <br />', $stock->signal) !!}
</p>
	
0 likes
4 replies
rodrigo.pedra's avatar

You can use the array_combine php function

<p style="font-size:15.5px; color:black; font-weight:900;">
    @foreach(array_combine(explode(',', $stock->time_frame), explode(',', $stock->signal)) as $key => $value)
        {{ $key }}: {{ $value}}

        @unless($loop->last)
            <br /> <span style="padding-left:10px;">+</span> <br />
        @endunless
    @foreach
</p>

The $loop variable is available inside the @foreach loop and provides helpers values to handle edge cases such as first iteration, last iteration, etc. Please refer the docs for more about it:

https://laravel.com/docs/6.x/blade#the-loop-variable

I recall in the last thread we used str_replace, but in that case you didn't have to combine both arrays. If you want to do that in one line you can try:

{!! str_replace('+', '<br /> <span style="padding-left:10px;">+</span> <br />', implode('+', array_map(function ($value, $key) { return "{$key}: {$value}"; }, array_combine(explode(',', $stock->time_frame), explode(',', $stock->signal))))) !!}

But I think the first option is more readable and easier to mantain

FareedR's avatar

im using the first one because more readable , but somehow the foreach doesnt work . what i get is " 5: test2" , only trigger the last index .

@foreach(array_combine(explode(',', $stock->time_frame), explode(',', $stock->signal)) as $key => $value)
	{{ $key }}: {{ $value}}
	@unless($loop->last)
	<br /> <span style="padding-left:10px;">+</span> <br />
	@endunless
@endforeach

rodrigo.pedra's avatar

I tried this code:

@php($time_frame = '3,5')
@php($signal = 'test1,test2')

@foreach(array_combine(explode(',', $time_frame), explode(',', $signal)) as $key => $value)
    {{ $key }}: {{ $value}}
    @unless($loop->last)
        <br /> <span style="padding-left:10px;">+</span> <br />
    @endunless
@endforeach

To test the @foreach loop and it worked:

3: test1
            <br /> <span style="padding-left:10px;">+</span> <br />
        5: test2

Note I defined a $time_frame and $signal variables locally to test them out, you should keep your code.

Can you post the dd() of the $stock variable just for checking?

FareedR's avatar

sorry for the late reply . all is good now . thank you for your time sir

1 like

Please or to participate in this conversation.