weixin_33713350 2016-07-19 06:23 采纳率: 0%
浏览 556

json对象中只有一个数组

I have 5 tables for different files that user can upload. I would like to get all the files with corresponding data in one array so 5 files data in one array.

All the tables have same structure:

user_id, file_type, file_size, file_name, file_new_name, file_path, date_created 

In PHP I am using this query select * from degree_files, profile_pictures, cpr_files, backgroundcheck_files, video_files where degree_files.user_id = :user_id which gives me all 5 file data if I run it in workbench, but json object is only one array.

How can I show all the data in one array or what would be the right solution, because right now I am querying each table separately?

I tried:

$backgroundCheck = $user_home->runQuery("select * from degree_files, profile_pictures, cpr_files, backgroundcheck_files, video_files where degree_files.user_id = :user_id");
$backgroundCheck->execute(array(":user_id"=>$user_id));
$nanny_backgroundCheck_file = $backgroundCheck->fetchAll(PDO::FETCH_ASSOC);


$file_name = array();
foreach ($nanny_backgroundCheck_file as $c){
    $file_name[] = $c['file_name'];
}

$arr[] = array('file_name'=>$file_name);
echo json_encode($arr, JSON_UNESCAPED_UNICODE);

And AJAX call:

$.getJSON("PHP/nannyInfo.php", function(data) {
        //SELECT2 DATA
        $.each(data.nanny_backgroundcheck_file, function(index, data) {
        console.log(data);

        });

});

What I see in console.

enter image description here

  • 写回答

1条回答 默认 最新

  • 乱世@小熊 2016-07-19 07:54
    关注

    The query first. You're trying to get a single column from multiple tables, right? If so, I'd suggest this syntax:

    $sql = "
        select file_name from degree_files where user_id = :user_id
        UNION select file_name from profile_pictures where user_id = :user_id
        UNION select file_name from cpr_files where user_id = :user_id
        UNION select file_name from backgroundcheck_files where user_id = :user_id
        UNION select file_name from video_files where user_id = :user_id";
    

    Then, the actual SQL execution is mostly OK but I'd simplify it to:

    $backgroundCheck = $db->prepare($sql);
    $backgroundCheck->execute(array(":user_id"=>1)); // 
    $fileNames = $backgroundCheck->fetchAll(PDO::FETCH_COLUMN, 'file_name');
    
    echo json_encode($fileNames, JSON_UNESCAPED_UNICODE);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 网络科学导论,网络控制
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)