2013-03-14 200 views
0
<?php 
if(file_exists("upload.json")) 
{ 

// For GETTING Values as an Associative Array... 
$temp_array = array(); 
$temp_array = json_decode(file_get_contents('upload.json'),true); 

$upload_info = array('media_name'=>'b', 
'media_category'=>'v','media_info'=>'c','media_location'=>'x','media_artist'=>'z'); 

array_push($temp_array, $upload_info); 

file_put_contents('upload.json', json_encode($upload_info)); 
} 
else 
{ 
$upload_info =array('media_name'=>'b', 
'media_category'=>'v','media_info'=>'c','media_location'=>'x','media_artist'=>'z'); 

$json = json_encode($upload_info); 

$file = "upload.json"; 

file_put_contents($file, json_encode($json)); 

} 
?> 

我無法在一起追加JSON文件: 有沒有解決方案? 在此先感謝。如何在PHP中追加JSON文件?

我想按以下順序查看JSON文件。

{ 
    "upload": 
    { 
    "image":[ 
     { 
     "media_name": "b", 
     "media_category": "v", 
     "media_info": "c", 
     "media_location": "x", 
      "media_artist": "z" 
     }, 
     { 
     "media_name": "b", 
     "media_category": "v", 
     "media_info": "c", 
     "media_location": "x", 
     "media_artist": "z" 
     } 
    ] 
    } 
} 

我該怎麼辦?從這裏

$json_data = json_decode(file_get_contents('data.txt'), true); 
for ($i = 0, $len = count($json_data); $i < $len; ++$i) { 
    $json_data[$i]['num'] = (string) ($i + 1); 
} 
file_put_contents('data.txt', json_encode($json_data)); 

例如:

回答

3
<?php 
if(file_exists("upload.json")) 
{ 
    $temp_array = array(); 
    $temp_array = json_decode(file_get_contents('upload.json')); 
    $upload_info = array('media_name'=>'b','media_category'=>'v','media_info'=>'c','media_location'=>'x','media_artist'=>'z'); 
    array_push($temp_array->upload->image, $upload_info); 
    file_put_contents('upload.json', json_encode($temp_array)); 
} 
else 
{ 
    $upload_info = array(); 
    $upload_info['upload']['image'][] = array('media_name'=>'b','media_category'=>'v','media_info'=>'c','media_location'=>'x','media_artist'=>'z'); 
    $json = json_encode($upload_info); 
    $file = "upload.json"; 
    file_put_contents($file, $json); 
} 
?> 

這一個給你只是工作!