【问题标题】:php json_encode id column to stringphp json_encode id 列到字符串
【发布时间】:2016-04-15 18:36:14
【问题描述】:

我的数组是:

$response = [
    0 => [
        'id' => 'US',
        'text' => 'United States'
    ],
    1 => [
        'id' => 'CA',
        'text' => 'Canada'
    ],

    2 => [
        'id' => 'FR',
        'text' => 'France'
    ],
...
]

当我对其执行json_encode 时,由于某种原因,id 的值通过数组为 0:

{"id":0,"text":"United States"},
{"id":0,"text":"Canada"},
{"id":0,"text":"France"}

仅当列名称为 id 时才会发生这种情况,就像 json_encode 强制 ID 为数字一样。

知道如何在id 列中使用字符串吗?

【问题讨论】:

  • 我刚刚运行了您的确切代码,它工作正常吗?

标签: json php-5.6


【解决方案1】:

所有'id' => 'XX' 行之后都需要逗号。添加这些并运行 json_encode 后,它对我来说效果很好,id 都保留了它们的字符串值。

【讨论】:

  • 缺少的逗号只是一个错字
  • @Alucard 在这种情况下,您的代码对我来说工作正常,json_encode 返回[{"id":"US","text":"United States"},{"id":"CA","text":"Canada"},{"id":"FR","text":"France"}]。我正在使用 php 5.6.15。
【解决方案2】:

试试:

$response = [
    0 => [
        'id' => 'US',
        'text' => 'United States'
    ],
    1 => [
    'id' => 'CA',
        'text' => 'Canada',
    ],

    2 => [
    'id' => 'FR',
        'text' => 'France'
    ]
];

var_dump(json_encode($response, 20));

结果:

{
    "0": {"id": "US", "text": "United States"},
    "1": {"id": "CA", "text": "Canada"},
    "2": {"id": "FR", "text": "France"}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-02
    • 2014-06-02
    • 2019-07-15
    • 2011-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多