繁体   English   中英

JSON 到 PHP 关联数组

[英]JSON to PHP Associative array

你们中有人知道将它放入关联数组的好方法吗? 我试过json_decode但发现它没有多大帮助。

这是我需要放入关联数组的数据:

{
  "data": [
    {
      "name": "Joe Bloggs",
      "id": "203403465"
    },
    {
      "name": "Fred Bloggs",
      "id": "254706567"
    },
    {
      "name": "Barny Rubble",
      "id": "453363843"
    },
    {
      "name": "Homer Simpson",
      "id": "263508546"
    }
  ]
}

编辑:

接受答案后,我想起了为什么我认为 json_decode 不起作用。

而不是拥有这样的关联数组:

[0] => Array
(
    [name] => Joe Bloggs
    [id] => 203403465
)

我想要一个这样的:

Array
(
    [Joe Bloggs] => 45203340465
    [Fred Bloggs] => 65034033446
)

不幸的是,我当时忘记了这一点......但我现在已经解决了我的问题。

感谢您所有的帮助!

json_decode对我的数据有用

print_r(json_decode('{
       "data": [
          {
             "name": "Joe Bloggs",
             "id": "203403465"
          },
          {
             "name": "Fred Bloggs",
             "id": "254706567"
          },
          {
             "name": "Barny Rubble",
             "id": "453363843"
          },
          {
             "name": "Homer Simpson",
             "id": "263508546"
          }
       ]
    }
', true));

输出:

Array
(
    [data] => Array
        (
            [0] => Array
                (
                    [name] => Joe Bloggs
                    [id] => 203403465
                )

            [1] => Array
                (
                    [name] => Fred Bloggs
                    [id] => 254706567
                )

            [2] => Array
                (
                    [name] => Barny Rubble
                    [id] => 453363843
                )

            [3] => Array
                (
                    [name] => Homer Simpson
                    [id] => 263508546
                )

        )

)

将第二个参数设置为true返回一个关联数组。

你必须创建一个新数组

$json_array = json_decode($_POST['json'], true);
$assoc_array = array();

for($i = 0; $i < sizeof($json_array); $i++)
{
     $key = $json_array[$i]['name'];
     $assoc_array[$key] = $json_array[$i]['value'];
}

您将在 $assoc_array 中获得关联数组,现在可以使用索引直接访问。

我假设你的 json 来自 ajax ......(否则代码与 json_decode 一起工作)所以确保 js json 字符串化你的对象和

你需要在 json_decode 之前去掉斜杠;-) 在 php 中

暂无
暂无

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

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