I used to have a code block and it works fine, but in some cases it throws a PHP notification:
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 the code above and it works great.
$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 little confused why type conversion (array)does not work in this code. I know that json_decode($json, true)is the best option for converting json string to array, but is $json_array = (array) $json_obj;also a valid option.
When looking at var_dumpboth codes, it shows some difference, but print_rboth arrays are exactly the same.
I am curious to know why such different things happened in var_dumpboth, and how does the (array)casting type convert an object to an array in the first case?
, , - i.e. 1455260079 , 1455260079 , .
: https://3v4l.org/PULrp