简体   繁体   English

PHP多维数组转换为JSON

[英]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. 因此,我试图找出将MySql表数据转换为多维PHP数组或将该多维数组转换为json字符串的最佳方法。

Essentially what im trying to do is have a php include that returns the JSON string so i can iterate through it. 本质上,我想做的是拥有一个包含JSON字符串的php include,以便我可以对其进行迭代。 I am needing a single key with multiple values, so im not 100% sure that im headed in the right direction. 我需要具有多个值的单个键,所以我不能100%确保即时消息朝着正确的方向前进。

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? 因为我没有任何类型的索引?

That is not valid JSON. 那是无效的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: 在PHP方面,您将需要以下内容:

  1. For every row fetched from MySQL 对于从MySQL获取的每一行
    • $arr[$key] = <new array> $arr[$key] = <新数组>
    • for each package: 对于每个包装:
      • append package to $arr[$key] 将包附加到$arr[$key]
  2. echo out json_encode($arr) 回显json_encode($arr)

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: JS数组具有从索引0开始的隐式数组键。您所拥有的是一个完全有效的JS数组,等效于编写:

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. 您永远不要手工构建JSON字符串。 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. 使用本地数据结构(php数组/对象),然后对其进行json_encode()更加容易。 Ditto on the other end of the process - don't decode the string manually. 在过程的另一端也是如此-请勿手动解码字符串。 Convert to a native data structure (eg json_decode() , JSON.parse() ) and then deal with the native structure directly. 转换为本地数据结构(例如json_decode()JSON.parse() ),然后直接处理本地结构。

essentially, JSON is a transmission format, not a manipulation format. 本质上,JSON是一种传输格式,而不是一种操纵格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM