【问题标题】:json_decode() expects parameter 1 to be string, array given?json_decode() 期望参数 1 是字符串,给定数组?
【发布时间】:2015-06-25 12:20:56
【问题描述】:

这是我的数据,在Json_encode()之后

 Array
        (
            [{"customerId":"1","customer_name":"Jon_doe","amount":"12312312","billcode":"b1231","billname":"cashbilname","billcategorycode":"1234","billcategory":"utility","month":"May","year":"2015","txcode":"10","stationid":"152","station":"Coroom","operatorcode":"1200","operator":"jame","terminal":"ter12312","txdate":"12\/2\/2015","txtime":"12:21:22_PM"}] 
    => 
        )

现在我想将它解码回来,通过应用json_decode() 它会给出以下错误

json_decode() 期望参数 1 是字符串,给定数组

有什么好的建议吗?

【问题讨论】:

  • 你是如何编码的?看起来你在那里做错了什么。
  • 能否请您发布您的相关代码?
  • 您需要将该数组的第一项传递给json_decode;而不是整个数组。所以,json_decode($array[0])
  • 错误信息就是你的答案。你在谷歌上搜索过那个错误信息吗?你会得到很多结果。
  • json_encode 首先应该给你一个字符串,而不是你显示的数组,所以那里肯定有问题。显示您的代码,我们或许可以提供帮助

标签: php arrays json


【解决方案1】:

您的json 必须在string 中,而不是在array

$json_string = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
$json_array = json_decode($json_string);

$json_array : ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5];

如果您的jsonarray 中,您可以这样做:

$json_string_in_array = ['{"a":1,"b":2,"c":3,"d":4,"e":5}'];
$json_array = json_decode($json_string_in_array[0]);

【讨论】:

  • 说未定义的 0 索引
【解决方案2】:

json_encode() 返回一个字符串,所以我不知道如何从中获取一个数组,除非你自己将它存储在一个数组中,例如:

$json = [];
$json[] = json_encode($someArray);

相反,只需将其存储在非数组变量中:

$jsonString = json_encode($someArray);

然后你可以这样解码:

$decodedArray = json_decode($jsonString);

【讨论】:

    【解决方案3】:
    $jsonstr = '[{"customerId":"1","customer_name":"Jon_doe","amount":"12312312","billcode":"b1231","billname":"cashbilname","billcategorycode":"1234","billcategory":"utility","month":"May","year":"2015","txcode":"10","stationid":"152","station":"Coroom","operatorcode":"1200","operator":"jame","terminal":"ter12312","txdate":"12\/2\/2015","txtime":"12:21:22_PM"}]';
    $ar = json_decode($jsonstr,true); # json string to Array
    $obj = json_decode($jsonstr); # json string to Object
    var_dump($ar,$obj);
    

    【讨论】:

      猜你喜欢
      • 2015-07-12
      • 2017-01-11
      • 2021-01-13
      • 2016-04-30
      • 2014-12-09
      • 2017-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多