Marti Behamby
Marti Behamby

Reputation: 13

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"
  }
]

Upvotes: 0

Views: 101

Answers (2)

Akshay katale
Akshay katale

Reputation: 157

You can do like this...

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

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

Upvotes: 2

Kyaw Kyaw Soe
Kyaw Kyaw Soe

Reputation: 3360

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);
?>

Upvotes: 0

Related Questions