0

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

2 Answers 2

1

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]}

Addition:

When decoding the JSON you are able to do the opposite casting i.e. to array:

<?php
 $arr = (array)json_decode('{"0":[1,2,3],"1":[4,5,6]}');
 var_dump($arr);
 $obj = json_decode('{"0":[1,2,3],"1":[4,5,6]}');
 var_dump($obj);
?>

Output:

array(2) {
  [0]=>
  array(3) {
    [0]=>
    int(1)
    [1]=>
    int(2)
    [2]=>
    int(3)
  }
  [1]=>
  array(3) {
    [0]=>
    int(4)
    [1]=>
    int(5)
    [2]=>
    int(6)
  }
}
object(stdClass)#1 (2) {
  ["0"]=>
  array(3) {
    [0]=>
    int(1)
    [1]=>
    int(2)
    [2]=>
    int(3)
  }
  ["1"]=>
  array(3) {
    [0]=>
    int(4)
    [1]=>
    int(5)
    [2]=>
    int(6)
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Ok thanks. I solved setting 0 as *. In c the atoi would have converted it in 0
you can to the opposite casting when decoding the result i.e. $array = (array)json_decode('{"0":[1,2,3],"1":[4,5,6]}');
I've made a small add on to the answer to show how to do it and what's the difference.
0

You can force numeric keys with json_encode using JSON_FORCE_OBJECT flag :

var_dump(json_encode($b,JSON_NUMERIC_CHECK|JSON_FORCE_OBJECT));

3 Comments

ok it's working...now th string has index. But the executable doesnt work :(
Can you provide us the code so we can take a look ?
it's very long anyway the problem is there. Maybe the c/c++ json parse fails. It uses jute

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.