PHP/json_encode : dealing with mixed arrays and objects with numeric properties

标签 php json associative-array

我最近不得不解决遗留 PHP 应用程序中的一个错误。此应用程序接收来自另一个应用程序的请求,其格式为 JSON:

{
  "someList": [
    "item A",
    "item B"
  ],
  "ratings": {
    "0": 0.001234,
    "1": 0.0666,
    "2": 0.09876,
    "3": 0.777777
  }
}

当它被反序列化为本地 PHP“关联数组”时,列表和映射(具有键 0、1、2 和 3)看起来都像列表。没关系,我可以解决这个问题。但是,此应用程序会对该数据进行计算,并在以大致相同的格式序列化回 JSON 并将其发送到另一个应用程序之前向其中添加更多数据。这就是问题所在。开箱即用 json_encode($data) 以上结果:

{
  "someList": [
    "item A",
    "item B"
  ],
  "ratings": [
    0.001234,
    0.0666,
    0.09876,
    0.777777
  ]
}

我的 key 都不见了...

我看到我可以使用 JSON_FORCE_OBJECT la echo json_encode($data, JSON_FORCE_OBJECT) 但是我得到:

{
  "someList": {
    "0": "item A",
    "1": "item B"
  },
  "ratings": {
    "0": 0.001234,
    "1": 0.0666,
    "2": 0.09876,
    "3": 0.777777
  }
}

现在我在第一个列表中得到了我不想要的键。 有没有办法序列化这个 JSON,这样 someList 将是一个列表(无键)而 ratings 将是一个映射/对象(键为 0、1 、2 和 3)?

最佳答案

当在数组列表上调用 json_encode 时,数字索引从 0 开始,PHP 会将列表视为索引数组,而不是关联数组。要强制 php 将其视为关联数组,您可以在调用 json_encode 之前将数组转换为对象。

例子:

$somelist = ["item A", "item B"];
$ratings = [0.001234, 0.666, 0.09876, 0.777777];
$final = ['someList' => $somelist, 'ratings' => (object) $ratings];

echo json_encode($final);

输出:

{["item A","item B"],{"0":0.001234,"1":0.666,"2":0.09876,"3":0.777777}}

关于PHP/json_encode : dealing with mixed arrays and objects with numeric properties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52674710/

相关文章:

php - 如何为多文本列布局编程?以便文本流入多个列!

json - 使用带有 Rspec 的 Sinatra 测试 JSON

PHP MySQL 检查ID是否存在

php - 如何在 php 中使用 soap 调用 Web 服务

php artisan 迁移: PDOException could not find driver

javascript - 嵌套 JSON 对象

python - 在 python 中渲染格式化文本(当前使用 pyglet)

associative-array - 列表理解中的 Coffeescript assoc 数组语法

arrays - 如果提前声明数组,Bash 数组赋值会失败

mysql - 更新对 mysql 表的数组响应