PHP multidimensional array to JSON

后端 未结 2 1728
我在风中等你
我在风中等你 2020-12-20 06:17

So im trying to figure out the best way to get MySql table data into either a multidimensional PHP array or convert that multidimensional array into a json string.

E

相关标签:
2条回答
  • 2020-12-20 06:38

    That is not valid JSON. The structure you are looking for would be something like:

    [
     {"key1": ["package1", "package2", "package3"]},
     {"key2": ["package1", "package2", "package3", "package4"}]
              ^ An array as the value to the key "key1", "key2", etc..
    ]
    

    At the PHP side, you would need something like:

    1. For every row fetched from MySQL
      • $arr[$key] = <new array>
      • for each package:
        • append package to $arr[$key]
    2. echo out json_encode($arr)
    0 讨论(0)
  • 2020-12-20 06:45

    JS arrays have an implicit array keying, starting at index 0. What you've got is a perfectly valid JS array, the equivalent of having written:

    var x = []; // create new empty array
    x[0] = {"key1": .... }; // first object
    x[1] = {"key2": ....} // second object
    

    Note that the contents of your {} sub-objects is NOT valid.

    You should never EVER built a JSON string by hand. It's too unreliable and easy to mess up. It's just easier to use a native data structure (php arrays/objects), then json_encode() them. Ditto on the other end of the process - don't decode the string manually. Convert to a native data structure (e.g. json_decode(), JSON.parse()) and then deal with the native structure directly.

    essentially, JSON is a transmission format, not a manipulation format.

    0 讨论(0)
提交回复
热议问题