PHP循环解析JSON文件遇问题:count返回值始终为1
解决JSON解析为PHP对象导致count()异常与循环失效的问题
我来帮你搞定这个问题!你遇到的核心问题其实是json_decode()的默认行为在搞鬼——它把JSON里的对象解析成了PHP的stdClass实例,而不是你以为的数组。这就是为什么count($fileValue)总是返回1,但var_dump()却显示有2个属性的原因:count()作用在普通对象上时,默认只会返回1(除非对象实现了Countable接口)。
修复步骤:
1. 让json_decode()返回关联数组
调用json_decode()时,传入第二个参数true,这样JSON对象就会被解析成PHP关联数组,而非stdClass对象:
$fileValue = json_decode(fread($fileStream, filesize($linkyValues)), true);
2. 改用foreach遍历关联数组
因为你的JSON结构是带自定义键名(IMD、cvH)的对象,解析成数组后是关联数组,不能用数字索引的for循环遍历。换成foreach来遍历键值对,同时正确获取timeOut和删除过期项:
foreach ($fileValue as $key => $item) { $timeout = $item['timeOut']; if (time() >= $timeout) { unset($fileValue[$key]); } }
3. 完整修改后的代码
<?php $linkyValues = "./linky.json"; if (file_exists($linkyValues)) { $fileStream = fopen($linkyValues, 'r'); // 第二个参数传true,解析为关联数组 $fileValue = json_decode(fread($fileStream, filesize($linkyValues)), true); fclose($fileStream); // 现在count()会正确返回数组元素个数(这里是2) echo count($fileValue); // 遍历关联数组处理过期项 foreach ($fileValue as $key => $item) { $timeout = $item['timeOut']; if (time() >= $timeout) { unset($fileValue[$key]); } } $fileStream = fopen($linkyValues, 'w'); fwrite($fileStream, json_encode($fileValue)); fclose($fileStream); } ?>
为什么原来的代码失效?
- 原代码中
$fileValue是stdClass对象,count($fileValue)返回1是PHP对普通对象的默认计数行为。 $fileValue->item($i)这种写法完全错误,stdClass没有item()方法;用$fileValue[$i]访问对象也不对,对象不能通过数字索引访问属性。
内容的提问来源于stack exchange,提问作者Nadav Tasher
相关产品推荐
相关产品推荐

