根据特定学生证显示图片 [英] Display pictures based on specific student ID

查看:36
本文介绍了根据特定学生证显示图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,在从我的 sql 表中提取所有信息后,我将它们放入名为 response1 和 response2 的 2 个变量中.下面显示的是当前数组中的内容.我的目标是在每个学生旁边展示这些图片.如果图片不存在,它现在可能只是空白.所以我已经通过使用 base64 编码从 DB 中获取图片以显示,但我目前只为 id:20000001 执行此操作,因为我不确定如何为其他图像执行此操作.

So after pulling all the information from my sql tables, I put them into 2 variables called response1 and response2.Shown below are what's currently inside the arrays. My goal is to display the pictures, beside each student. If a picture doesn't exsist, it can just be blank for now. So i've gotten the picture from DB to display by using base64 encode, but i'm only currently doing it for the id:20000001, since i'm not sure how to do it for other ones.

我有个想法,也许可以更换

I had an idea to maybe replace

student_image= findItemByID(response2,'20000001'); 

student_image= findItemByID(response2,element.id); ?
但不确定这是否是正确的逻辑?

student_image= findItemByID(response2,element.id); ?
but not sure if this is correct logic?

在我的 Object.keys 最终循环中,我应该如何修复 html+='<img src="data:image/jpeg;base64,'+student_image.photo+'">' 所以它添加了特定 id 的图像?

Inside my Object.keys final loop, how should I fix html+='<img src="data:image/jpeg;base64,'+student_image.photo+'">' so that it adds the image of the specific id?

Response1 对象数组:

Response1 array of object:

0: {Class_Student_Group: 1, names: "Lastname1, Firstname1", id: 20000001}
1: {Class_Student_Group: 2, names: "Lastname2, Firstname2", id: 20000002}
2: {Class_Student_Group: 3, names: "Lastname3, Firstname3", id: 20000003}
3: {Class_Student_Group: 5, names: "Lastname4, Firstname4", id: 20000004}
4: {Class_Student_Group: 3, names: "Lastname5, Firstname5", id: 20000005}

Response2 对象数组:

Response2 array of objects:

0: {student_id: "20000001", photo: ""}
1: {student_id: "20000001", photo: "/9j/4AAQSkZJRgABAQAAAQABAAD/4QB6RXhpZgAASUkqAAgAAA…9a1EtFKAnd09f/rVlwfdFbVw7LPIoOAGNYwjc/SIaxR//2Q=="}
2: {student_id: "20000002", photo: ""}
3: {student_id: "20000003", photo: ""}

最后:

1: Array(4)
0: {Class_Student_Group: 1, names: "Lastname1, Firstname1", id: 20000001}
1: {Class_Student_Group: 1, names: "Lastname9, Firstname9", id: 20000009}
2: {Class_Student_Group: 1, names: "Lastname15, Firstname15", id: 20000015}
3: {Class_Student_Group: 1, names: "Lastname19, Firstname19", id: 20000019}
length: 4
__proto__: Array(0)
2: (4) [{…}, {…}, {…}, {…}]
3: (4) [{…}, {…}, {…}, {…}]

到目前为止的输出:

<script type="text/javascript">





$(document).ready(function() {



var response= <?php echo json_encode($table); ?>;
var response2= <?php echo json_encode($result); ?>;





function findItemByID(arr, id) {
  return arr.find((photoObj) => {
    return photoObj.photo.trim().length !== 0 && photoObj.student_id === id
  })
}


var final = {}

response.forEach(function(element) {
  final[element.Class_Student_Group] = final[element.Class_Student_Group] || [];
  final[element.Class_Student_Group].push(element);

});




let student_image =''


Object.keys(final).forEach(function(Group) {

      let html = '';

      //add the table opening tag to the html variable
      html += '<table>';
      //Append the 'category' header
      html += '<tr>';
      html += '<td><h1>'+"Group"+ Group+'</h1></td>';
      html += '</tr>';

      // Loop through the results for this 'category'
      student_image= findItemByID(response2,'20000001');
      final[Group].forEach(function(element) {   
      var randomImage = images[Math.floor(Math.random() * images.length)];
        var names = element.names;
        var id=element.id;

        var img = "<img src=' " + randomImage+ " ' />";
        html += '<tr>';
        html += '<td><p>' + names + '</p></td> ';
        html += '<td><p>' + id + '</p></td> ';
        html+='<img src="data:image/jpeg;base64,'+student_image.photo+'">'


        html += '</tr>';
      });
      //add the table closing tag to the html variable
      html += '</table>'; 

      $('#tables_container').append(html);
});








});

</script>

推荐答案

好的.这里发生了很多事情.

OK. Quite a few things going on here.

  1. 基本上 findItemByID() 函数不起作用的原因是因为 A.(我必须假设您知道这一点)您传入每次调用时都使用相同的 ID,B. 把它放在你调用 final[Group].forEach(function(element) 之前,你不能传入正确的id 的值,因为 id 是该 element 变量和 C. === 的属性是一个严格相等运算符,这意味着它仅在值相同并且它们是相同类型时才返回 true.在一个对象数组中,该值是一个字符串并且另一个是数字.
  2. 你做的很多事情都是乱序的.退后一步,试着想想这段代码的目的是做什么,一步一步地写,像我在这里所做的那样,在可行的时候把你的步骤分解成函数.查看我对您的代码所做的更改以及我添加的注释.通常,在编写代码时,您希望使用函数来提高可读性,并将它们分开,以便在任何给定时间处理尽可能少的复杂性.表格的工作原理类似于 table -> row -> column -- 以这种方式编写代码.
  3. 我对 HTML 中的图像使用 Base64 一无所知,但请查看 此链接 表明您在此处提供的数据不起作用.查看已接受答案中的解码器.
  4. 我改变了您对 final 对象进行迭代的方式.这可能主要是品味问题,但对我来说它更具可读性.您可以在此处
  5. 使用更好的名字!如果您不尝试记住 responseresponse2 中的数据,那么当您试图找出某些东西损坏的原因时,就会容易得多.只需将它们称为 studentDataArrayimageDataArray 或其他名称即可.
  1. Basically the reason(s) the findItemByID() function wasn't working was because A. (and I have to assume you knew this) you were passing in the same ID every time it was called, B. by putting it before you called final[Group].forEach(function(element) you couldn't pass in the right value for the id, as the id is a property of that element variable, and C. === is a strict equality operator, which means it only returns true if the values are the same and they are the same type. In one array of objects that value is a string and in the other it's a number.
  2. You are doing a lot of things out of order. Take a step back and try to think about what this code is intended to do and write it one step at a time, and break your steps into functions whenever practical like I have done here. Look over the changes I have made to your code, and the comments I added. Generally when writing code you want to use functions to make things more readable, and break them apart so you are dealing with the least amount of complexity as possible at any given time. A table works like table - > row - > column -- write your code that way.
  3. I don't know anything about using Base64 for images in HTML, but a look at this link suggests that the data you have supplied here won't work. Check out the decoder in the accepted answer.
  4. I changed the way you were iterating over your final object. This is probably mostly a matter of taste, but to me it's more readable. You can learn more about it here
  5. Use better names! It's so much easier when you're trying to figure out why something is broken if you aren't also trying to remember what data is in response vs response2. Just call them studentDataArray and imageDataArray or something.

$(document).ready(function () {
    loadTable();
});

let array1 = [
    { Class_Student_Group: 1, names: "Lastname1, Firstname1", id: 20000001 }
    , { Class_Student_Group: 2, names: "Lastname2, Firstname2", id: 20000002 }
    , { Class_Student_Group: 3, names: "Lastname3, Firstname3", id: 20000003 }
    , { Class_Student_Group: 5, names: "Lastname4, Firstname4", id: 20000004 }
    , { Class_Student_Group: 3, names: "Lastname5, Firstname5", id: 20000005 }
]

let array2 = [{ student_id: "20000001", photo: "" }
    , { student_id: "20000001", photo: "/9j/4AAQSkZJRgABAQAAAQABAAD/4QB6RXhpZgAASUkqAAgAAA…9a1EtFKAnd09f/rVlwfdFbVw7LPIoOAGNYwjc/SIaxR//2Q==" }
    , { student_id: "20000002", photo: "" }
    , { student_id: "20000003", photo: "" }];

function findItemByID(arr, id) {
    return arr.find((photoObj) => {
        return photoObj.photo.trim().length !== 0 && photoObj.student_id == id // because the id property in the student object is a number and in the photo array it's a string, change this to '==', which evaluates '2' as equal to 2. === only returns true if they are the same type
        //also you have been checking for a student_id property here, which doesn't exist on the second array's objects, so this wasn't returning anything
    })
}

function getFinalObject(response) {
    var final = {}

    response.forEach(function (element) {
        final[element.Class_Student_Group] = final[element.Class_Student_Group] || [];
        final[element.Class_Student_Group].push(element);

    });

    return final;

}

function appendHtmlToDoc(final, response2, images) {

    let html = '';

    //add the table opening tag to the html variable
    html += '<table>';

    for (let Group in final) {               //this will loop through final's properties, in this case, the 'groups'
        if (final.hasOwnProperty(Group)) {    //use hasOwnProperty to make sure you aren't looping through irrevelant properties (https://stackoverflow.com/questions/8312459/iterate-through-object-properties)

            //Append the 'category' header
            html += '<tr>';
            html += '<td><h1>' + "Group" + Group + '</h1></td>';
            html += '</tr>';

            // Loop through the results for this 'category'
            final[Group].forEach(function (element) { //you already have the Group array in the Group variable

                let student_image = findItemByID(response2, element.id);    //search for the image data using this element's id property

                // var randomImage = images[Math.floor(Math.random() * images.length)]; //should pass 'images' into this function, but I don't know where it came from and randomImage/img isn't used in the code you provided, so I removed it
                var names = element.names;
                var id = element.id;

                // var img = "<img src=' " + randomImage + " ' />";
                html += '<tr>';
                html += '<td><p>' + names + '</p></td> ';
                html += '<td><p>' + id + '</p>';
                if (student_image) { //check if something was returned when you searched for the photo, otherwise you'll have a blank image here
                    html += '<td><img src="data:image/jpeg;base64, ' + student_image.photo + '"></td>'; //I don't know anything about using images in HTML with base64, but a look at this link (https://stackoverflow.com/questions/8499633/how-to-display-base64-images-in-html) suggests that what you have provided won't work
                }
                //I also added a td around your img tag

                html += '</tr>';
            });
        }
    }

    //add the table closing tag to the html variable
    html += '</table>';
    //console.log(html)
    $('#tables_container').append(html);

}

function loadTable() {

    //move your php script calls here

    let finalObj = getFinalObject(array1);
    appendHtmlToDoc(finalObj, array2);
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tables_container"></div>

这篇关于根据特定学生证显示图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆