【问题标题】:Text file count returning as 2 when there only one array当只有一个数组时,文本文件计数返回 2
【发布时间】:2017-12-19 15:21:08
【问题描述】:

谁能告诉我解码后的内容何时返回 count = 2 而不是 1?

我假设如果解码数组在那里,那么它的计数应该是 1,因为它里面没有多个数组对象。

例子:

// Count 1
Array ( [chat_id] => 414 [inserted] => 1500038898 )

// Count 2 
Array ( 
[0] => Array ([chat_id] => 414 [inserted] => 1500038898) 
[1] => Array ([chat_id] => 415 [inserted] => 1500038898) 
)

文本文件内容:

{"chat_id":414,"inserted":1500038898}

代码:

// Get file contents
$fileContents = json_decode(file_get_contents($file), true);

if($fileContents !== NULL){
    // Push decoded contents to temp array
    $decoded_data = $fileContents;
    print_r(count($decoded_data));
}

解码:

Array ( [chat_id] => 414 [inserted] => 1500038898 )

【问题讨论】:

  • 它也在计算最后一个空行,可能是?但是由于它有两个键,它正在使用它们吗?另外,它没有被[]包围,这是数组表示法。
  • 问问自己 - 为什么它应该返回 1?
  • 为什么你认为它应该返回 1?
  • var_dump($decoded_data);die;
  • count — Count all elements in an array, or something in an object 有任何问题吗?

标签: php json file count


【解决方案1】:

老兄,正如我在 my first comment 中告诉你的,它不是 JSON 中的数组。好的,所以 JSON 数据不符合您输入的要求。将您的 JSON 数据更改为:

[{"chat_id":414,"inserted":1500038898}]

这应该给你1而不是2。以上就是单次入境所需要的。两条记录的示例,就像您想要的那样:

[{"chat_id":414,"inserted":1500038898}, {"chat_id":415,"inserted":1500038898}]

我希望我解释清楚。你错过了[]。它应该是一个对象数组[{}],而不仅仅是一个对象{}

【讨论】:

    猜你喜欢
    • 2016-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-12
    • 2013-06-12
    • 1970-01-01
    • 2014-05-19
    相关资源
    最近更新 更多