user14194891
user14194891

Reputation:

PHP loop through JSON array from database

I have this JSON array stored in my database

[{
    "prodid": 1,
    "optionsids": [],
    "extrasids": ["1"]
}, {
    "prodid": 2,
    "optionsids": [],
    "extrasids": ["4"]
}]

I am storing it as an array and when I retrieve it in PHP I am going through this and I am 100 % sure it is wrong

 $productsarray=json_encode($row['productids']);
 $obj = json_decode($productsarray, TRUE);

so I can then loop to get the prodid value

$products='';
foreach( $obj as $key => $value) {
    $value = get_object_vars($value);
    $products = $products.$value;
}

But I am getting an Invalid argument supplied for foreach() error which means that $obj is not an array right? idk how to fix this i have tried various things but with no results.

Upvotes: 1

Views: 86

Answers (1)

IncredibleHat
IncredibleHat

Reputation: 4104

If this is the string stored in your database column:

[{
    "prodid": 1,
    "optionsids": [],
    "extrasids": ["1"]
}, {
    "prodid": 2,
    "optionsids": [],
    "extrasids": ["4"]
}]

If its already stored as json, you dont need to json_encode it again when you pull it out of the database.

The following is all you would need to do to get all the prodid into a single array to use:

$items = json_decode($row['productids'],true);
$products = [];
foreach($items as $item) {
    $products[] = $item['prodid'];
}
var_dump($products);// for debug to see the result

$product_string = implode(',',$products);// to put all prodid in a single string

Upvotes: 1

Related Questions