Home > OS >  Big PHP array to readable json
Big PHP array to readable json

Time:10-17

I have made a website using bootstrap 5, and most of it is jQuery Ajax. The cards are loaded at page load using a PHP script, which works like a charm. But I've come to where i would like the select input to work. When you click on it, you can choose if you want to change the sorting to creation_date, modified_date or just sort by default which is sorted by id.

Here's what it looks like visually.

I am using PHP to create an array and then use json_encode to make it accessible from the front-end over at jquery.

Here's the code I'm using:

    while($row = mysqli_fetch_array($sql)) {

    $i  ;
    $id = $row['id']; // Get id of card.
    $r = $row['tittel']; // Get title value of card.
    $o = $row['opprettet']; // Get value for 'created' date for the card

    // I use this function to loop through all the values and put them in an array.
    for ($x = 1; $x <= 2; $x  ){
        $jsonarray['card'] = array(
            'id' => $x,
            'title' => $r,
            'opprettet' => $o,
        );
    }

    echo json_encode($jsonarray, JSON_UNESCAPED_SLASHES);
}

The code above outputs to this json:

{
   "card":{
      "id":2,
      "title":"Pizza",
      "opprettet":"15/10/2022 02:50"
   }
}{
   "card":{
      "id":2,
      "title":"Spaghetti a la capriadgadg",
      "opprettet":"15/10/2022 05:08"
   }
}{
   "card":{
      "id":2,
      "title":"test ingrediens",
      "opprettet":"15/10/2022 13:14"
   }
}{
   "card":{
      "id":2,
      "title":"Middag for den mette, eller en enda mindre middag for 2.",
      "opprettet":"16/10/2022 13:51"
   }
}{
   "card":{
      "id":2,
      "title":"Fruktfat for den feite",
      "opprettet":"16/10/2022 13:55"
   }
}

I have tried examples from other stack overflow articles, reddit and other websites but none of them are doing this in a while function like i am. How can i make this read-able to the javascript in the front-end? Once i get the PHP code okay, i can make it read-able to front-end and show the contents of the json in the cards as planned.

CodePudding user response:

I suggest you put all objects in an array and encode after all rows are fetched. Something like this (adjusted your code):

$json = [];
while($row = mysqli_fetch_array($sql)) {
    $i  ;
    $id = $row['id']; // Get id of card.
    $r = $row['tittel']; // Get title value of card.
    $o = $row['opprettet']; // Get value for 'created' date for the card

    // I use this function to loop through all the values and put them in an array.
    for ($x = 1; $x <= 2; $x  ){
        $json[] = ["card" => [
            'id' => $x,
            'title' => $r,
            'opprettet' => $o,
        ]];
    }
}
echo json_encode($json, JSON_UNESCAPED_SLASHES);
  • Related