Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

hackflybit's avatar

how to convert json data into strings to display on the frontend

hello I need your help to convert json data to strings, this problem is when I am storing product data in the form of json into mysql, but I find it difficult to display on the frontend side

this is my data in db

{"produk": ["XplorAA", "HG3000", "System 5000"]}

how do I display on the frontend side

 @foreach ($sph as $x)
	<tr>
		<td>{{ $x->produk}}</td>
	</tr>
@endforeach

result {"produk": ["XplorAA", "HG3000", "System 5000"]}	

if use 
<td>{!! json_encode($x->produk)!!}</td>
result "{\"produk\": [\"XplorAA\", \"HG3000\", \"System 5000\"]}"

in my controller just

$sph = Sph::all();

My wish is to be able to display product data in

produk: XplorAA, HG3000, System 5000

or

XplorAA, HG3000, System 5000

can you help me to fix it. Can you help me to fix it, if you have any questions please ask.

0 likes
3 replies
LaryAI's avatar
Level 58

To display the product data as a string on the frontend, you can use the implode() function in PHP to join the array values with a separator. Here's an example:

@foreach ($sph as $x)
    <tr>
        <td>{{ implode(', ', json_decode($x->produk)) }}</td>
    </tr>
@endforeach

In this example, we're using json_decode() to convert the JSON string to a PHP array, and then using implode() to join the array values with a comma and space separator.

Alternatively, if you want to display the product data without the "produk:" label, you can use the implode() function directly on the JSON string:

@foreach ($sph as $x)
    <tr>
        <td>{{ implode(', ', json_decode($x->produk)->produk) }}</td>
    </tr>
@endforeach

In this example, we're using json_decode() to convert the JSON string to a PHP object, and then accessing the produk property to get the array values.

hackflybit's avatar

@LaryAI the code is error

implode(): Argument #1 ($pieces) must be of type array, string given
Snapey's avatar

There are a couple of issues with Lary's response

first, the json_decode requires a second parameter of true if it is to return an array

second, the array will be a single element of produk with the values as children of that so we need to get the sub-array

@foreach ($sph as $x)
    <tr>
        <td>{{ implode(', ', json_decode($x->produk, true)['produk']) }}</td>
    </tr>
@endforeach

Actually Lary's answer is ok, if you remember to access produk using object syntax

$product = '{"produk": ["XplorAA", "HG3000", "System 5000"]}';

implode(', ',json_decode($product)->produk);

Please or to participate in this conversation.