Skip to content
Advertisement

How to parse json array from mysql?

I have this data but I can’t parse it in the way I want. this is what I get:

{
  "navigations": {
    "title": "Facebook",
    "link": "https://facebook.com",
    "behavior": "EXTERNAL"
  }
}

And what I expect to see:

{
  "navigations": [
    {
      "title": "Facebook",
      "url": "https://facebook.com",
      "behavior": "INAPP"
    },
    {
      "title": "Youtube",
      "url": "https//youtube.com",
      "behavior": "INAPP"
    }
  ]
}

I have more results in my database but not more than 12 result so, i want to fetch data in the format i expect. I tried to do it using fetch_array but no success.

This is my PHP code:

$query_update_navigations = $db->prepare("SELECT title, link, behavior FROM navigation_tabs WHERE secret_api_key=?");
$query_update_navigations->bind_param("s", $_SESSION['secret_api_key']);
$query_update_navigations->execute();

$rows = array();
$result = $query_update_navigations->get_result();

while($rows1 = $result->fetch_assoc()) {
    $rows['navigations'] = $rows1;
}

$store_path = '../apis/navigation_tabs/';
$file_name = $_SESSION['secret_api_key'] . '.json';
$sign_constants = json_encode($rows);

file_put_contents($store_path . $file_name, $sign_constants);

I searched for an answer but nothing solved my issue 🙁

Advertisement

Answer

You need to push the row onto the array, not overwrite it each time.

$rows = array('navigations' => []);
$result = $query_update_navigations->get_result();

while($rows1 = $result->fetch_assoc()) {
    $rows['navigations'][] = $rows1;
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement