Search code examples
javascriptphpjsonlivesearch

Search in a JSON file


I'm perform a live I use this to get the json file

<?php
if(mysqli_num_rows($result) > 0)
{
  while($row1 = mysqli_fetch_array($result))
  {
        $output["name"][]=$row1["name"];
        $output["email"][]=$row1["email"];
  }
}

$fp = fopen('results.json', 'w');
fwrite($fp,json_encode($output));
fclose($fp);
?>

and i got something like this in the json file

{
"name":["Marinasy","test","test","Nath"],
"email":["[email protected]","test@test","test@trs","nath@trs"]
}

But I need something like the code below to do a search. Is there any way to get a JSON like this instead of the JSON above? or how I do search in the code above?

[
  {
    "name":"Marinasy",
    "email": "[email protected]"
  },
  {
    "name":"Test",
    "email": "test@test"

  },
  {
    "name":"Nath",
    "email": "nath@trs"
  }
]

Solution

  • Change this

    $output["name"][]=$row1["name"];
    $output["email"][]=$row1["email"];
    

    to

    $output[] = [
        "name"=>$row1["name"],
        "email"=>$row1["email"]
    ];
    

    Full code here

    <?php
        if (mysqli_num_rows($result) > 0) {
            $output = [];
            while ($row1 = mysqli_fetch_array($result)) {
                $output[] = [
                    "name" => $row1["name"],
                    "email" => $row1["email"]
                ];
            }
        }
    
        $fp = fopen('results.json', 'w');
        fwrite($fp, json_encode($output));
        fclose($fp);
    ?>