Sunday, August 06, 2017
php to javascript via json_encode - beware negative keys in sparse arrays
The json-encode function in php is a neat way of getting data into javascript - but ...
... be careful with arrays.
If you have a non-sparse array then that can be encoded using json-encode($thisArray, true);
But a sparse array needs to be encoded the normal way - json-encode($thisArray); - and this creates an OBJECT rather than an ARRAY in javascript (which can't handle associative arrays)
The problem comes if your sparse array has a negative key. I hit this - the key will list if you iterate through the keys (albeit AFTER the positive keys!) but you can't access the value.
Ugh!
... be careful with arrays.
If you have a non-sparse array then that can be encoded using json-encode($thisArray, true);
But a sparse array needs to be encoded the normal way - json-encode($thisArray); - and this creates an OBJECT rather than an ARRAY in javascript (which can't handle associative arrays)
The problem comes if your sparse array has a negative key. I hit this - the key will list if you iterate through the keys (albeit AFTER the positive keys!) but you can't access the value.
Ugh!