简体   繁体   English

PHP-多维数组转换为Json

[英]PHP - Multidimensional Array to Json

This is a bit of a reverse engineering question, but I want to know how to write in PHP a proper multidimensional array in PHP that outputs the following javascript array. 这是一个反向工程问题,但是我想知道如何用PHP在PHP中编写适当的多维数组,并输出以下javascript数组。

      [
        {
          "key": "Basic Planners",
          "values": [{"x": "YourPhone","y": 150}, 
                     {"x": "Universe X3","y": 300},
                     {"x": "ePhone 74s","y": 1500}, 
                     {"x": "NextUs","y": 50}, 
                     {"x": "Humanoid","y": 500
                    }]
        }, {
          "key": "No-Namers",
          "values": [{"x": "YourPhone","y": 300}, 
                     {"x": "Universe X3","y": 250}, 
                     {"x": "ePhone 74s","y": 400}, 
                     {"x": "NextUs","y": 150}, 
                     {"x": "Humanoid","y": 900}]

        }, {
          "key": "Feature Followers",
          "values": [{"x": "YourPhone","y": 350}, 
                     {"x": "Universe X3","y": 900}, 
                     {"x": "ePhone 74s","y": 100}, 
                     {"x": "NextUs","y": 500}, 
                     {"x": "Humanoid","y": 250}]

        }, {
          "key": "Hipsters & Elites",
          "values": [{"x": "YourPhone","y": 200}, 
                     {"x": "Universe X3","y": 350}, 
                     {"x": "ePhone 74s","y": 50}, 
                     {"x": "NextUs","y": 800}, 
                     {"x": "Humanoid","y": 100}]
        }
      ]

The following code should do the trick 以下代码可以解决问题

$phpArray = array(
    array(
        'key' => 'Basic Planners',
        'values'=> array(
            array('x' => 'YourPhone', 'y' => 150),
            array('x' => 'Universe X3', 'y' => 300),
            array('x' => 'ePhone 74s', 'y' => 1500),
            array('x' => 'NextUs', 'y' => 50),
            array('x' => 'Humanoid', 'y' => 500),
        )
    ),
    /* and so on... */
);

echo json_encode($phpArray);

PHP Manual PHP手册

For the JSON Objects use array("key" => value, ...) 对于JSON对象,请使用array("key" => value, ...)

for the JSON Arrays use array(arg0, arg1, arg2, ...) 对于JSON数组,请使用array(arg0, arg1, arg2, ...)

Then just nest these various groupings. 然后只需嵌套这些不同的分组。 This should output the desired JSON. 这应该输出所需的JSON。

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

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