【问题标题】:json_encode change number into stringjson_encode 将数字更改为字符串
【发布时间】:2014-07-07 08:16:13
【问题描述】:

我有一个数组,其中包含一些字符串值和一些数值。我用过

json_encode

将数组转换为 json 数组,但它将数字值转换为我不想要的字符串。

 [["India","2"],["Panama","1"]]

我试过了

JSON_NUMERIC_CHECK

作为 json_encode 中的第二个参数,它在 localhost 上工作正常,但在线显示错误。

Use of undefined constant JSON_NUMERIC_CHECK - assumed '

我正在使用 cakephp 2.3

【问题讨论】:

  • 您到底希望输出是什么? [["India",2],["Panama",1]] 将是无效的 json
  • @andrew 为什么那应该是无效的?
  • 在 cakephp 2.3 中使用 '[["India","2"],["Panama","1"]]' 的 json 解码数组时遇到什么错误?跨度>
  • @Ryan Vincent 我正在使用 Highchart,但我遇到了错误。我需要这种格式的数组 [["India",2],["Panama",1]]

标签: arrays json cakephp-2.3


【解决方案1】:

我在网上猜你有一个旧版本的 PHP:

JSON_NUMERIC_CHECK(整数)

将数字字符串编码为数字。 自 PHP 5.3.3 起可用。

当你进行 JSON 编码时,如果 PHP 知道它不是一个字符串,它就不会有引号。 如果您需要手动完成,您可以执行以下操作:

<?php

  function json_numeric($array)
  {
     if (is_array($array) || is_object($array)) {
        foreach($array as &$prop) {
            if (is_numeric($prop)) {
                $prop = intval($prop);
            }
            if (is_object($prop) || is_array($prop)) {
                $prop = json_numeric($prop);
            }
        }
     }
     return $array;
  }

  $x = array("a" => 1, "b" => "2", "c"=>array("d"=>1, "e"=>"2"));
  echo json_encode(json_numeric($x));
  //{"a":1,"b":2,"c":{"d":1,"e":2}}
  $y = new stdClass();
  $y->a = 1;
  $y->b = "2";
  echo json_encode(json_numeric($y));
  //{"a":1,"b":2}
?>

【讨论】:

  • 谢谢。此错误是由于 php 版本造成的。我更新了我的 php 版本,现在可以正常工作了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-05
  • 2018-07-04
  • 1970-01-01
  • 2013-09-15
  • 2021-02-27
相关资源
最近更新 更多