I am build a simple GUI for my linux executable. I am just using HTML/Javascript and PHP. My problem is calling my excutable with system
with a json string as parameter my string has not index in array. Here's my code
$b = [0=>[1,2,3],1=>[4,5,6]];
var_dump(json_encode($b,JSON_NUMERIC_CHECK));
string(17) "[[1,2,3],[4,5,6]]"
I need the string with key because the c/c code requires an index, why is it happening? How to solve it? Thanks
CodePudding user response:
JSON is actually a stringified Javascript an if you want to represent a key => value structures these structures should be Objects or Associative arrays. PHP will assume any associative array having only numbers as keys to an regular array, so you should cast your array to an object. Objects couldn't have numbers as keys (properties) so they will be converted to strings, so you will actually have '0' => [1,2,3]
... and etc.
The easiest way is just t cast your array to object. Look at the example below:
<?php
$array = [0=>[1,2,3],1=>[4,5,6]];
$object = (object) $array;
print json_encode($array);
print json_encode($object);
?>
Output:
[[1,2,3],[4,5,6]]{"0":[1,2,3],"1":[4,5,6]}
CodePudding user response:
You can force numeric keys with json_encode using JSON_FORCE_OBJECT
flag :
var_dump(json_encode($b,JSON_NUMERIC_CHECK|JSON_FORCE_OBJECT));