【问题标题】:PHP convert Array to JSON issue? [duplicate]PHP将数组转换为JSON问题? [复制]
【发布时间】:2015-07-02 15:11:22
【问题描述】:

当我print_r($arr) 类似Array ( [0] => Hello [1] => world); 时输出。

我尝试使用以下代码转换为 JSON 字符串。

$result['result'] = $arr;
json_encode($result);

这会产生这个 JSON 字符串:

{"result" : { "0" : "hello" , "1" : "world"}}

预期的结果是这样的:

{ "result" : ["hello" , "world"]}

我可以做些什么来获得所需的输出?

【问题讨论】:

  • 这真的是你的代码吗?数组从何而来?第二个结果看起来像你会得到的。
  • 我想要像{ "result" : ["hello" , "world"]} 这样的格式……但没有得到。是的,这是我的代码
  • 检查此链接都显示相同的输出jsonviewer.stack.hu
  • print_r($arr) 输出看起来像Array ( [0] => Hello [1] => world);
  • 是的,$arr = array("Hello", "world");你会得到你想要的结果,所以显示你的 $arr ;)

标签: php arrays json


【解决方案1】:
$result['result'] = array_values($arr);
json_encode($result);

仅使用值。

【讨论】:

    【解决方案2】:

    很简单,请使用下面给出的代码。

    $arr = array("0"=>'hello',"1"=>'world');
    $result['result'] = array_values($arr);
    echo json_encode($result);
    

    谢谢 阿米特

    【讨论】:

      【解决方案3】:

      需要这样做:

      $result['result'] = array_values($arr);
      

      【讨论】:

      • 数组 ([0] => 你好 [1] => 世界); -> 如果这真的是他得到的输出,那么 $arr 不是一个对象,它是一个数组;)
      • 好吧,这是我的错误 :)
      【解决方案4】:

      将您的数组值放入数组的结果键。然后它将打印所需的结果。

      $arr = array("0"=>'one',"1"=>'two');
      $result['result'] = array_values($arr);
      echo json_encode($result);
      

      在线演示http://sandbox.onlinephpfunctions.com/code/c4227f1bbeb675c6950d9e4e0f189477153dff3e

      【讨论】:

        猜你喜欢
        • 2017-09-09
        • 1970-01-01
        • 2015-07-02
        • 2016-07-07
        • 2013-06-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-18
        相关资源
        最近更新 更多