0

I have this array in the controller after the submitted form holds in variable $product.

[
    {
        "id": 2,
        "name": "nancy",
        "cost": 34,
        "quantity": 0,
        "barcode": 12345,
        "category_id": 2,
        "created_at": "2020-07-05T16:04:10.000000Z",
        "updated_at": "2020-07-09T04:06:09.000000Z"
    },
    {
        "id": 5,
        "name": "jk",
        "cost": 100,
        "quantity": 2,
        "barcode": 147258,
        "category_id": 2,
        "created_at": "2020-07-08T20:34:56.000000Z",
        "updated_at": "2020-10-18T13:09:16.000000Z"
    }
]

How can I access the properties in objects like id, name, barcode ?

1
  • I think you actually mean to say you have an array of objects and as such the output is actually: [0 => '{"id":2,"name":"nancy","cost":34,"quantity":0,"barcode":12345,"category_id":2,"created_at":"2020-07-05T16:04:10.000000Z","updated_at":"2020-07-09T04:06:09.000000Z"}', 1 => '{"id":5,"name":"jk","cost":100,"quantity":2,"barcode":147258,"category_id":2,"created_at":"2020-07-08T20:34:56.000000Z","updated_at":"2020-10-18T13:09:16.000000Z"}']; ? Commented Oct 19, 2020 at 16:21

2 Answers 2

2

If you want to make it as array of array.

$products = json_decode($products, true);  // Return array of array.

foreach($products as $product){
    echo $product['name']; 
}
Sign up to request clarification or add additional context in comments.

6 Comments

You are converting it into array and then accessing it as object. It will not work
it assosiative array
in PHP json_decode convert json data into PHP associated array For Ex: $php-array= json_decode($json-data, true); print_r($php-array);
what i'm saying is after converting $products to array, you can't access properties like $product->name, now it should be $product['name']
php.net/manual/en/function.json-decode.php by using true as the second argument, you are converting it to an associative array. Arrow syntax -> does not work anymore
|
1

Just decode it, use json_decode

$products = json_decode($products, true);  // When TRUE, JSON objects will be returned as associative arrays

foreach($products as $product){
    echo $product['id']; 
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.