php - 从 php 中的文件夹中读取文件并列出 json 文件中的条目

标签 php json

我正在尝试使用 php 加载文件夹中的所有图像,然后构建一个表并从 json 文件中提取文本并将其放在每个图像旁边。目标是让 json 看起来像这样。

{
    "Car1": {
        "year":"2012"
    },
    "Car2": {
        "year":"2011"
    },
    "Car3": {
        "year":"2009",
        "milage":"10,204"
    }
}

Car1、Car2 名称最终也将与文件夹中实际图像的名称相匹配。所以我想抓取图像和 json 文件中的正确部分,并构建一个列出所有内容的表格。到目前为止,我有下面的 php,但我不太确定如何将它们放在一起,正如您在下面看到的,它现在只是分开的。关于如何结合下面的 php 来实现我描述的结果有什么建议吗?


6/1 编辑(新代码使用下面的答案)。这是在我想要输出所有这些的页面上,&letter 变量是从另一页上的表单传递的。但是当该表单提交并且该页面触发时,什么也没有发生。我做错了什么吗?

$letter = $_POST['letter'];

//Call the path of the cars for the chosen letter
$path = "/images/PartsCars/".$letter."/";
$temp_files = scandir($path);

//Call the path for the json file in the chosen letter subfolder
$data = json_decode($string, true);

//Sort the pictures in this folder alphabetically
natsort($temp_files);

echo '<table cellspacing="5" cellpadding="5">';

//Loop through all pictures and json elements to build out the page
foreach($temp_files as $file) 
{
    if($file != "." && $file != ".." && $file != "Thumbs.db" && $file != basename(__FILE__)) 
    {
        echo '<tr>';
        echo '<td><a href="'.$url.$file.'" title="'.$file.'"><img src="'.$url.$file.'" alt="'.$file.'" style="width:300px;height:200px;"/></a></td>';
        $info = pathinfo($file);
        $file_name =  basename($file,'.'.$info['extension']);
        echo '<td>'.print_r($data['$file_name']).'</td>';
        echo '</tr>';
    }
}

echo '</table>';

最佳答案

我使用 php json_decode 以方便使用,并使用 print_r 进行演示,您可以使用 foreach 循环正确打印出来

$path = "./images/PartsCars/A/";
$temp_files = scandir($path);
$string = file_get_contents("/images/PartsCars/A/sample.json");
data = json_decode($string, true);

natsort($temp_files);

echo "<table>";

foreach($temp_files as $file) 
{
    if($file != "." && $file != ".." && $file != "Thumbs.db" && $file != basename(__FILE__)) 
    {
        echo '<tr>';
        echo '<td><a href="'.$url.$file.'" title="'.$file.'"><img src="'.$url.$file.'" alt="" /></a></td>';
        $info = pathinfo($file);
        $file_name =  basename($file,'.'.$info['extension']);
        echo '<td>'.print_r(data['$file_name']).'</td>';
        echo '</tr>'
    }
}
echo '</table>';

关于php - 从 php 中的文件夹中读取文件并列出 json 文件中的条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10758176/

相关文章:

Javascript 检查空字段,安全吗?

javascript - WCF 服务接受简单的 JSON 字符串但拒绝带有 400 错误的 JSON 集

java - 尝试使用 JSON 将 http 发布到服务器,获取 : java. io.UnsupportedEncodingException

php - 从我的数据库中格式化一个字符串,这样就会有空格

php - Laravel 子域在重定向时丢失 session

javascript - 根据 Javascript 变量值从 PHP 获取数据到 Javascript

PHP 将 Windows-1251 转换为 UTF 8

json - 具有 echo 框架的 golang API

php - 使用 Joins 在 Laravel View 中显示 Json 数据

php - AJAX、POST、JSON 和 PHP : How do I do it?