Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between json_decode($var) and (object)json_decode($var, true)

is there any difference between json_decode($var) and (object)json_decode($var, true)?

While recently working at certain piece of code in Joomla virtuemart, I came to a puzzled situation. Virtumart uses (object)json_decode($var, true) for its cartObject, and if I change it to simple json_decode($var), it shows some error afterwards. On further debugging I found the cart structure as:

stdClass Object
(
    [cartProductsData] => Array
        (
        )
    [vendorId] => 0
    [automaticSelectedShipment] => 
    [automaticSelectedPayment] => 
    [order_number] => 
    [BT] => Array
        (
        )
    [ST] => Array
        (
        )
)

Though on changing code, i.e, json_decode($var), the result is:

stdClass Object
(
    [cartProductsData] => Array
        (
        )
    [vendorId] => 0
    [automaticSelectedShipment] => 
    [automaticSelectedPayment] => 
    [order_number] => 
    [BT] => stdClass Object
        (
        )
    [ST] => stdClass Object
        (
        )
)

So BT and ST are objects now,rather than arrays as earlier they are, but how? Any explanation would be appreciated.

like image 402
Anant Avatar asked Nov 08 '22 11:11

Anant


1 Answers

This is because, of json_decode() return type

In json_decode($var), it returns the whole json data as object, including inner components. (All levels)

But, json_decode($var, true) returns whole json data in array structure, including inner components. (All levels)

So, when (object)json_decode($var, true) is used, json_data returns data as array and only the outermost or main array (1st level) gets casted into object.

like image 186
Robin Panta Avatar answered Nov 14 '22 23:11

Robin Panta