storage.json:
{"544aee0b0a00f":{"p_name":"testname","p_about":null,"file":"images\/1.png"}}
{"548afbeb42afe":{"p_name":"testname2","p_about":null,"file":"images\/2.png"}}
{"549afc8c8890f":{"p_name":"testname3","p_about":null,"file":"images\/3.jpg"}}现在,开头带有字母的数字是uniqid()函数,在将项写入文件时调用该函数。
<?php
$storage_file = 'storage.json';
$storage = file_get_contents($storage_file);
$storage = json_decode($storage,true);
$storage = empty($storage) ? array() : $storage;
print_r($storage)
?>现在我尝试显示json文件中的所有记录,但是只有当我在文件中有1条记录,如果我有超过1条记录时,它才能工作,因为就像这里(3条记录)一样,我得到的结果是简单的文本: Array()。
有人能帮我吗?我被困在这里,不知道该怎么解决这个问题
发布于 2014-12-12 15:07:36
如果您一次尝试全部解码,由于需要一个数组来容纳多个对象,所以由于JSON无效,它将失败。
相反,您需要逐一解码每一行:
<?php
$storage_file = 'storage.json';
$storage = file_get_contents($storage_file);
$lines = explode("\n", $storage);
for ($i=0;$i<count($lines);$i++)
{
$data = json_decode($lines[$i],true);
print_r($data);
}
?><?php
$storage_file = 'storage.json';
$storage = file_get_contents($storage_file);
$lines = explode("\n", $storage);
foreach ($lines as $line)
{
$data = json_decode($line,true);
print_r($data);
}
?><?php
$storage_file = 'storage.json';
$storage = file_get_contents($storage_file);
$lines = explode("\n", $storage);
foreach ($lines as $line)
{
$data = json_decode($line, true);
foreach ($data as $key => $value) {
echo "p_name = ".$data[$key]["p_name"]."\n";
}
}
?>发布于 2014-12-12 15:23:47
由于上面提到的meda代码工作非常好,所以我将使用foreach。
$storage_file = 'storage.json';
$storage = file_get_contents($storage_file);
$lines = explode("\n", $storage);
foreach ($lines as $str){
$data = json_decode($str,true);
print_r($data);
}发布于 2014-12-12 16:53:47
我迟到了,但希望这个答案对某人有用。
在每个文件行中都有有效的json。
所以最好的解决方案是使用file():
$data = array_map(function($row){
return json_decode($row);
}, file('storage.json'));
print_r($data);file为我们提供了文件行数组(因此,我们不需要炸掉它)array_map将json_decode应用于每一行只为得到pname:
$data = array_map(function($row){
$a = json_decode($row);
return $a[key($a)]['pname'];
}, file('storage.json'));
print_r($data);添加
使用此代码创建文件:
$new_id = count($storage);
$uid = uniqid();
$storage[$uid] = $new_record;
file_put_contents($storage_file,json_encode($storage), FILE_APPEND); 但更好的方法是:
//get current database:
$data = json_decode(file_get_contents($filename), true);
//...
$uid = uniqid();
$data[$uid] = $new_record;
file_put_contents($filename, json_encode($storage));因此,对于所有数据,我们总是有有效的json。
而且总是可以让它变得简单如下:
//get current database:
$data = json_decode(file_get_contents($filename), true);https://stackoverflow.com/questions/27446317
复制相似问题