1

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.

2
  • 1
    If its already stored as json, you dont need to json_encode it again when you pull it out of the database. Also when using true in json_decode, the entire $obj will be an associative array, so the subsequent get_object_vars can be unpredictable with an associative array fed into it. Commented Sep 4, 2020 at 15:26
  • Please provide desired result Commented Sep 4, 2020 at 15:39

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.