簡體   English   中英

PHP的JSON讀取文件

[英]php json read file

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( )

有人可以幫我嗎? 我有點卡在這里,不知道該怎么辦才能解決問題

如果您嘗試一次全部解碼,則將由於無效的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";
    }
}

?>

正如上面提到的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);
}

遲到了,但希望這個答案對某人有用。

每個文件行中都有有效的json。
因此使用file()最佳解決方案:

$data = array_map(function($row){
  return json_decode($row);
}, file('storage.json'));

print_r($data);
  • file給我們文件行數組(因此,我們不需要分解它)
  • array_mapjson_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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM