2016-08-03 137 views
0

我制作了简单的文本编辑器,现在正在处理图像上传和图像管理器。我已经设置了管理器来读取所有图像的.json文件,并且它工作正常。问题是PHP脚本实际上是将新添加的图像写入该json。将目录中的所有文件写入json

$file = "images.json"; 
$arr_data = array(); 

foreach(glob('/uploads/*') as $image) { 
    $arr_data = array(
     'link' => $image, 
     'tag' => 'images', 
    ); 
} 

$jsondata = file_get_contents($file); 
$arr_data = json_decode($jsondata, true); 

array_push($arr_data,$jsondata); 

$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT); 
file_put_contents($file, $jsondata)); 

我正在

警告:array_push()预计参数1是阵列

甚至寿提供阵列数据。如何解决这个问题?

+0

Easies方式是输出'$ arr_data'并检查。请记住 - 如果错误告诉你参数不是数组 - 它实际上不是数组。 –

+0

你是从一个空文件开始的,即这个'images.json' – RiggsFolly

+0

它在打印后显示空数组。是的,我有空的json文件 –

回答

1

如果你是从一个空文件即images.json那么你第一次运行这两条线

$jsondata = file_get_contents($file); 
$arr_data = json_decode($jsondata, true); 

第二行会改变$arr_data为布尔可能。由于json_decode()将无法​​将nothing转换为数组。

所以添加这个初始化文件使用

<?php 
$file = "images.json"; 
file_put_contents($file, '[]'); // init the file 

您还重用$arr_data变量,以便修改,这也和你正在重写新的阵列以及

$file = "images.json"; 
file_put_contents($file, '[]'); // init the file 

$arr_data = array(); 

foreach(glob('/uploads/*') as $image) { 
    // amended to not reuse $arr_data 
    // ameded to not overwrite the array as you build it 
    $new_arr[] = array('link' => $image, 'tag' => 'images'); 
} 

$jsondata = file_get_contents($file); 
$arr_data = json_decode($jsondata, true); 

array_push($arr_data,$new_arr); 

$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT); 
file_put_contents($file, $jsondata)); 
+0

所以我编辑了json文件并在其中添加了占位符图像。在运行脚本之后,它显示了完全相同的错误,并且json文件已被更改为空 –

+0

还发现了变量重用 – RiggsFolly

+0

并且您正在覆盖从glob创建的数组 – RiggsFolly