user616
user616

Reputation: 855

PHP multidimensional array to JSON

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.

Essentially what im trying to do is have a php include that returns the JSON string so i can iterate through it. I am needing a single key with multiple values, so im not 100% sure that im headed in the right direction.

I want to assign multiple values to the same key, for example:

[{"key1": "package1", "package2", "package3"}, {"key2": "package1", "package2", "package3", "package4"}]

I think that is not going to work right? Because i dont have any type of index's?

Upvotes: 1

Views: 8102

Answers (2)

UltraInstinct
UltraInstinct

Reputation: 44434

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)

Upvotes: 4

Marc B
Marc B

Reputation: 360572

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.

Upvotes: 1

Related Questions