Earlier I have some block of code and it was working fine, But in some case it is throwing PHP notice:
Here is the code:
$json = '{"1455260079":"Tracking : #34567808765098767 USPS","1455260723":"Delivered","1455261541":"Received Back"}';
$json_obj = json_decode($json);
$json_array = (array) $json_obj;
var_dump($json_array);
print_r($json_array);
echo $json_array["1455260079"]."\n";
output:
array(3) {
["1455260079"]=>
string(34) "Tracking : #34567808765098767 USPS"
["1455260723"]=>
string(9) "Delivered"
["1455261541"]=>
string(13) "Received Back"
}
Array
(
[1455260079] => Tracking : #34567808765098767 USPS
[1455260723] => Delivered
[1455261541] => Received Back
)
Notice: Undefined index: 1455260079 in /in/PULrp on line 14
So I changed above code with below code and it's working fine.
$json_array = json_decode($json, true);
var_dump($json_array);
print_r($json_array);
echo $json_array["1455260079"]."\n";
output:
array(3) {
[1455260079]=>
string(34) "Tracking : #34567808765098767 USPS"
[1455260723]=>
string(9) "Delivered"
[1455261541]=>
string(13) "Received Back"
}
Array
(
[1455260079] => Tracking : #34567808765098767 USPS
[1455260723] => Delivered
[1455261541] => Received Back
)
Tracking : #34567808765098767 USPS
But Here I am a bit confused why (array)
type casting conversion is not working in this code. I know json_decode($json, true)
is best option to convert json string into array but $json_array = (array) $json_obj;
is also a valid option.
While looking into var_dump
of both code it showing some difference but the print_r
of both array are exactly same.
I am curious to know why such different occurred in var_dump
of both and how (array)
type casting is converting object to array in first case?
I also noticed that it's happening if the key is number i.e. 1455260079 in my case, if I change key 1455260079 to some string its working as expected.
you can see output of the complete code at: https://3v4l.org/PULrp