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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With