BigJobbies
BigJobbies

Reputation: 4055

PHP looping over JSON objects in my database

I'm storing some values using the mysql json field type, in Sequel Pro I'm seeing them as follows

["feature1","feature2","feature3","feature4"]

In my PHP file, I can print out the contents using

echo $plan->features;

but what I want to do is look over each one so I can style them, but the problem is when I stick it in a foreach loop I get the following:

Invalid argument supplied for foreach()

My loop is straightforward

foreach ($plan->features as $features) {
}

I'm not sure I'm doing things right.

Upvotes: 0

Views: 75

Answers (1)

Naresh Kumar P
Naresh Kumar P

Reputation: 4210

This is a JSON String

["feature1","feature2","feature3","feature4"]

User json_decode() for the above string

$string = json_decode($teststring,TRUE);

And after that you can for loop the variable or foreach the variable

foreach($string as $single_value)
{
     echo $single_value.'<br>';
}

Output:

feature1

feature2

feature3

feature4

Upvotes: 6

Related Questions