Ranjank
Ranjank

Reputation: 133

how to display json object with two array in html by using two for loops

I have this form:

Form image

Personal details in storing into personal table and book into book table.

The table is linked by the Id field in personal table and UserId field in book table. 5 books can be inserted against 1 personal information. userId of 5 books records will be same as personal information Id.

So, now to the problem:

I am echoing both tables data as json array (2 arrays) in php and wanted to display it in html via loop. Personal information is getting displayed but books are not displaying. It might also be possible that my approach is not good. So, please give me some good alternative if you have any.

JSON data:

{
   "personaldetails":[
      {
         "id":"79",
         "FirstName":"Elon",
         "MiddleName":"",
         "LastName":"Musk",
         "Gender":"Male",
         "Location":"New York",
         "Email":"[email protected]",
         "Mobile":"1234567890"
      },
      {
         "id":"78",
         "FirstName":"Elon",
         "MiddleName":"",
         "LastName":"Musk",
         "Gender":"Male",
         "Location":"New York",
         "Email":"[email protected]",
         "Mobile":"1234567890"
      },
      {
         "id":"77",
         "FirstName":"Elon",
         "MiddleName":"",
         "LastName":"Musk",
         "Gender":"Male",
         "Location":"New York",
         "Email":"[email protected]",
         "Mobile":"1234567890"
      },
      {
         "id":"76",
         "FirstName":"Elon",
         "MiddleName":"",
         "LastName":"Musk",
         "Gender":"Male",
         "Location":"New York",
         "Email":"[email protected]",
         "Mobile":"1234567890"
      },
      {
         "id":"75",
         "FirstName":"Elon",
         "MiddleName":"",
         "LastName":"Musk",
         "Gender":"Male",
         "Location":"New York",
         "Email":"[email protected]",
         "Mobile":"1234567890"
      },
      {
         "id":"74",
         "FirstName":"Elon",
         "MiddleName":"",
         "LastName":"Musk",
         "Gender":"Male",
         "Location":"New York",
         "Email":"[email protected]",
         "Mobile":"1234567890"
      },
      {
         "id":"73",
         "FirstName":"Elon",
         "MiddleName":"",
         "LastName":"Musk",
         "Gender":"Male",
         "Location":"New York",
         "Email":"[email protected]",
         "Mobile":"1234567890"
      },
      {
         "id":"72",
         "FirstName":"Elon",
         "MiddleName":"",
         "LastName":"Musk",
         "Gender":"Male",
         "Location":"New York",
         "Email":"[email protected]",
         "Mobile":"1234567890"
      },
      {
         "id":"71",
         "FirstName":"Elon",
         "MiddleName":"",
         "LastName":"Musk",
         "Gender":"Male",
         "Location":"New York",
         "Email":"[email protected]",
         "Mobile":"1234567890"
      },
      {
         "id":"70",
         "FirstName":"Elon",
         "MiddleName":"",
         "LastName":"Musk",
         "Gender":"Male",
         "Location":"New York",
         "Email":"[email protected]",
         "Mobile":"1234567890"
      },
      {
         "id":"69",
         "FirstName":"Elon",
         "MiddleName":"",
         "LastName":"Musk",
         "Gender":"Male",
         "Location":"New York",
         "Email":"[email protected]",
         "Mobile":"1234567890"
      },
      {
         "id":"68",
         "FirstName":"Elon",
         "MiddleName":"",
         "LastName":"Musk",
         "Gender":"Male",
         "Location":"New York",
         "Email":"[email protected]",
         "Mobile":"1234567890"
      }
   ],
   "bookdetails":[
      {
         "UserId":"79",
         "BookTitle":"who am i",
         "BookGenre":"inspiration",
         "BookWriter":"modi",
         "BookDescription":"this book is all about the struggle one faces all his life.no matter what he does he never get any attention"
      },
      {
         "UserId":"79",
         "BookTitle":"a walk to remember",
         "BookGenre":"romance",
         "BookWriter":"peter",
         "BookDescription":"a wall in the rainy season where all "
      },
      {
         "UserId":"78",
         "BookTitle":"who am i",
         "BookGenre":"inspiration",
         "BookWriter":"modi",
         "BookDescription":"this book is all about the struggle one faces all his life.no matter what he does he never get any attention"
      },
      {
         "UserId":"78",
         "BookTitle":"a walk to remember",
         "BookGenre":"romance",
         "BookWriter":"peter",
         "BookDescription":"a wall in the rainy season where all "
      },
      {
         "UserId":"77",
         "BookTitle":"who am i",
         "BookGenre":"inspiration",
         "BookWriter":"modi",
         "BookDescription":"this book is all about the struggle one faces all his life.no matter what he does he never get any attention"
      },
      {
         "UserId":"77",
         "BookTitle":"a walk to remember",
         "BookGenre":"romance",
         "BookWriter":"peter",
         "BookDescription":"a wall in the rainy season where all "
      },
      {
         "UserId":"76",
         "BookTitle":"who am i",
         "BookGenre":"inspiration",
         "BookWriter":"modi",
         "BookDescription":"this book is all about the struggle one faces all his life.no matter what he does he never get any attention"
      },
      {
         "UserId":"76",
         "BookTitle":"a walk to remember",
         "BookGenre":"romance",
         "BookWriter":"peter",
         "BookDescription":"a wall in the rainy season where all "
      },
      {
         "UserId":"75",
         "BookTitle":"who am i",
         "BookGenre":"inspiration",
         "BookWriter":"modi",
         "BookDescription":"this book is all about the struggle one faces all his life.no matter what he does he never get any attention"
      },
      {
         "UserId":"75",
         "BookTitle":"a walk to remember",
         "BookGenre":"romance",
         "BookWriter":"peter",
         "BookDescription":"a wall in the rainy season where all "
      },
      {
         "UserId":"74",
         "BookTitle":"who am i",
         "BookGenre":"inspiration",
         "BookWriter":"modi",
         "BookDescription":"this book is all about the struggle one faces all his life.no matter what he does he never get any attention"
      },
      {
         "UserId":"74",
         "BookTitle":"a walk to remember",
         "BookGenre":"romance",
         "BookWriter":"peter",
         "BookDescription":"a wall in the rainy season where all "
      },
      {
         "UserId":"73",
         "BookTitle":"who am i",
         "BookGenre":"inspiration",
         "BookWriter":"modi",
         "BookDescription":"this book is all about the struggle one faces all his life.no matter what he does he never get any attention"
      },
      {
         "UserId":"73",
         "BookTitle":"a walk to remember",
         "BookGenre":"romance",
         "BookWriter":"peter",
         "BookDescription":"a wall in the rainy season where all "
      }
   ]
}

PHP API:

 $personal = $db->prepare('select Id,FirstName,MiddleName,LastName,Gender,Location,Email,Mobile from personaldetails ORDER BY Id DESC');
    $personal->execute();
    $json_data=array();



    foreach($personal as $row)//foreach loop  
    {  

        $json_array['id']=$row['Id'];  
        $json_array['FirstName']=$row['FirstName'];  
        $json_array['MiddleName']=$row['MiddleName'];  
        $json_array['LastName']=$row['LastName']; 
        $json_array['Gender']=$row['Gender']; 
        $json_array['Location']=$row['Location']; 
        $json_array['Email']=$row['Email']; 
        $json_array['Mobile']=$row['Mobile'];
        array_push($json_data,$json_array);  

}  

    $books = $db->prepare('select UserId,BookTitle,BookGenre,BookWriter,BookDescription from bookdetails ORDER BY UserId Desc'); 
    $books->execute();
    $json_data1=array();

     //$bookNo = 0;
    foreach($books as $row)//foreach loop  
    {  
        //$bookNo++;
        //$json_array1['BookNo']= $bookNo;  
        $json_array1['UserId']=$row['UserId']; 
        $json_array1['BookTitle']=$row['BookTitle']; 
        $json_array1['BookGenre']=$row['BookGenre'];  
        $json_array1['BookWriter']=$row['BookWriter']; 
        $json_array1['BookDescription']=$row['BookDescription']; 

    //here pushing the values in to an array  
    array_push($json_data1,$json_array1);  

}  

    header('Content-type: application/json');
    echo json_encode(array("personaldetails"=>$json_data,"bookdetails"=>$json_data1));

JavaScript in HTML

<script>
    $.getJSON(url, function(data) {
        if (data) {
            var personalArr = (data.personaldetails).length;
            console.log(personalArr);
            var bookArr = (data.bookdetails).length;
            console.log(bookArr);
            for (var i = 0; i < personalArr; i++) {
                var a = data.personaldetails[i].Id;
                $("#personalDiv").append('<div>' + '<p>' + 'FirstName:' + data.personaldetails[i].FirstName + 
                                         '<br/>' + 'MiddleName:' + data.personaldetails[i].MiddleName + 
                                         '<br/>' + 'LastName:' + data.personaldetails[i].LastName + 
                                         '<br/>' + 'Location:' + data.personaldetails[i].Location + 
                                         '<br/>' + 'Email:' + data.personaldetails[i].Email + 
                                         '<br/>' + 'Mobile:' + data.personaldetails[i].Mobile + '<br/>' + '</p>' + '</div>');
                for (var j = 0; j < bookArr; j++) {
                    var b = data.bookdetails[j].UserId;
                    if (a == b) {
                        $("#personalDiv").append('<div>' + '<p>' + 'BookTitle:' + data.bookdetails[j].BookTitle + 
                                                 '<br/>' + 'BookGenre:' + data.bookdetails[j].BookGenre + 
                                                 '<br/>' + 'BookWriter:' + data.bookdetails[j].BookWriter + 
                                                 '<br/>' + 'BookDescription:' + data.bookdetails[j].BookDescription + 
                                                 '<br/>' + '</p>' + '</div>');
                    }
                }
            }
        }
        console.log(data);
        alert("Roger that" + JSON.stringify(data));
    });

    $(function() {
        loadData();
    });
</script>
<div class="grid" id="postjson"></div>
<div class="grid" id="personalDiv"></div>

Please give me some alternative solution two cause but my approach is very time consuming at large data context.

here is my desired output( all in single html div) :

enter image description here

Upvotes: 0

Views: 945

Answers (1)

CodeGodie
CodeGodie

Reputation: 12132

You need to use JOINs in your mysql query, its the proper and most efficient way. Once you have your result set, you can then iterate over the results and clean it, re-organize it to match how you want your front-end to see it. I would do it in this manner:

SQL:

SELECT
    p.Id, p.FirstName, p.MiddleName, p.LastName, p.Gender, p.Location, p.Email, p.Mobile,
    b.BookTitle, b.BookGenre, b.BookWriter, b.BookDescription
FROM personaldetails AS p
LEFT JOIN bookdetails AS b ON b.UserId = p.Id
ORDER BY p.Id DESC

Sample DB Result:

//sample
$db_result_set = [
    [
        "Id" => 1,
        "FirstName" => "John",
        "MiddleName" => "Bob",
        "LastName" => "Doe",
        "BookTitle" => "The Boy",
        "BookGenre" => "Fiction",
        "BookWriter" => "Mark Doe",
        "BookDescription" => "about some boy",
    ],
    [
        "Id" => 1,
        "FirstName" => "John",
        "MiddleName" => "Bob",
        "LastName" => "Doe",
        "BookTitle" => "The Girl",
        "BookGenre" => "Fiction",
        "BookWriter" => "Jane Doe",
        "BookDescription" => "about some girl",
    ],
    [
        "Id" => 1,
        "FirstName" => "John",
        "MiddleName" => "Bob",
        "LastName" => "Doe",
        "BookTitle" => "The Man",
        "BookGenre" => "Fiction",
        "BookWriter" => "Pat Doe",
        "BookDescription" => "about some man",
    ],
    [
        "Id" => 23,
        "FirstName" => "Bobby",
        "MiddleName" => "Bob",
        "LastName" => "Doe",
        "BookTitle" => "The Girl",
        "BookGenre" => "Fiction",
        "BookWriter" => "Jane Doe",
        "BookDescription" => "about some girl",
    ],
    [
        "Id" => 23,
        "FirstName" => "Bobby",
        "MiddleName" => "Bob",
        "LastName" => "Doe",
        "BookTitle" => "The Man",
        "BookGenre" => "Fiction",
        "BookWriter" => "Pat Doe",
        "BookDescription" => "about some man",
    ]
];

PHP:

$final = [];
foreach ($db_result_set as $u) {
    if (!is_array($final[$u["Id"]])) {
        $final[$u["Id"]]= [
            "Id" => $u["Id"],
            "FirstName" => $u["FirstName"],
            "MiddleName" => $u["MiddleName"],
            "LastName" => $u["LastName"],
        ];
    }
    $final[$u["Id"]]["books"][] = [
        "BookTitle" => $u["BookTitle"],
        "BookGenre" => $u["BookGenre"],
        "BookWriter" => $u["BookWriter"],
        "BookDescription" => $u["BookDescription"],
    ];
}
echo "<pre>";
print_r($final);
echo "</pre>";

RESULT:

Array
(
    [1] => Array
        (
            [Id] => 1
            [FirstName] => John
            [MiddleName] => Bob
            [LastName] => Doe
            [books] => Array
                (
                    [0] => Array
                        (
                            [BookTitle] => The Boy
                            [BookGenre] => Fiction
                            [BookWriter] => Mark Doe
                            [BookDescription] => about some boy
                        )

                    [1] => Array
                        (
                            [BookTitle] => The Girl
                            [BookGenre] => Fiction
                            [BookWriter] => Jane Doe
                            [BookDescription] => about some girl
                        )

                    [2] => Array
                        (
                            [BookTitle] => The Man
                            [BookGenre] => Fiction
                            [BookWriter] => Pat Doe
                            [BookDescription] => about some man
                        )

                )

        )

    [23] => Array
        (
            [Id] => 23
            [FirstName] => Bobby
            [MiddleName] => Bob
            [LastName] => Doe
            [books] => Array
                (
                    [0] => Array
                        (
                            [BookTitle] => The Girl
                            [BookGenre] => Fiction
                            [BookWriter] => Jane Doe
                            [BookDescription] => about some girl
                        )

                    [1] => Array
                        (
                            [BookTitle] => The Man
                            [BookGenre] => Fiction
                            [BookWriter] => Pat Doe
                            [BookDescription] => about some man
                        )

                )

        )

)

Now you can easily send this to your front end for a better iteration and rendering.

Upvotes: 1

Related Questions