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

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 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝