Ad

I Can't Convert Object To An Array

- 1 answer

I am trying to make a shopping cart API route and I am stuck with this problem because when I am using this statement $carts = \Cart::session($session)->getContent(); I get an object like this:

"cart": {
    "1": {
        "id": 1,
        "name": "Tort cu biscuiți",
        "price": 20,
        "quantity": "1",
        "attributes": {
            "image_path": "http://127.0.0.1:8000/storage/images/AkiGKJdxjKNtyoVI034RPL1drLsMntUxLfzqZplV.jpeg"
        },
        "conditions": []
    },
    "2": {
        "id": 2,
        "name": "Tort cu biscuiți",
        "price": 20,
        "quantity": 2,
        "attributes": {
            "image_path": "http://127.0.0.1:8000/storage/images/IkAhenLttHWaRD58hNZ460ykWCq7q1sih3vI9H5V.jpeg"
        },
        "conditions": []
    }
}

and I want to convet this to be array of objects. I tryied $cart->toArray(); and didn't work, also I tiyed (array) $cart and I get this:

"cart": {
    "\u0000*\u0000items": {
        "1": {
            "id": 1,
            "name": "Tort cu biscuiți",
            "price": 20,
            "quantity": "1",
            "attributes": {
                "image_path": "http://127.0.0.1:8000/storage/images/AkiGKJdxjKNtyoVI034RPL1drLsMntUxLfzqZplV.jpeg"
            },
            "conditions": []
        },
        "2": {
            "id": 2,
            "name": "Tort cu biscuiți",
            "price": 20,
            "quantity": 2,
            "attributes": {
                "image_path": "http://127.0.0.1:8000/storage/images/IkAhenLttHWaRD58hNZ460ykWCq7q1sih3vI9H5V.jpeg"
            },
            "conditions": []
        }
    }
}

may I know what is the problem?

Ad

Answer

You can do it manuel like this:

$carts = \Cart::session($session)->getContent();

if ($carts) {
    $cartsArray = json_decode($carts);
    foreach($cartsArray->cart as &$cart){
        $cart = (array) $cart;
    }
}

dd($cartsArray);

Ad
source: stackoverflow.com
Ad