将JSON转换为PHP关联数组

4

你们中有谁知道把这个数据放入关联数组的好方法吗?我已经尝试过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
)

很遗憾,在那个时候我忘记了这一点...但是现在我已经解决了我的问题。

感谢您的所有帮助!


只是以防万一...除了超过24小时的uid之外,不允许存储Facebook用户数据... - helle
1
@helle:那已经不是这样了。 - Yuliy
3个回答

9

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 会返回一个关联数组。


谢谢你的回答,webbiedave。如果你看一下我在helle评论中的最后一条评论,你就会知道我做了什么。对于我想要的回应,点赞! - OdinX

3

你需要创建一个新数组

$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中得到你的关联数组,现在可以直接使用索引进行访问。

1
这正是我需要的。 - Adam Knowles

2
我假设你的 JSON 是通过 Ajax 获取的...(否则,代码将使用 json_decode)。所以请确保 JavaScript 使用 JSON.stringify() 方法将对象转换为 JSON 字符串,并且在 PHP 中需要在 json_decode() 之前使用 stripslashes() 方法。

它不是通过AJAX获取的,但出于某种原因,现在当我使用json_decode时它按照我最初的预期工作。非常奇怪,因为当我删除stripslashes时,它也可以正常工作...可能是我以前尝试时弄错了什么。感谢helle让我重新回到正确的轨道上:) - OdinX

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接