I am aware of the ongoing questions but none seem to have what i need. I also am not sure how to formulate the question I am here to ask..
I am looking for the folowing output and I cant figur out how to do this:
{"email@email":{"name":"acc name1","email":"email@email","password":"password1"},
"email@email":{"name":"acc name1","email":"email@email","password":"password1"},
"email@email":{"name":"acc name1","email":"email@email","password":"password1"}}
This is what I have tried so far and it gives me the folowing output,
{"email@email":{"name":"acc name1","email":"email@email","password":"password1"}}
{"email@email":{"name":"acc name1","email":"email@email","password":"password1"}}
{"email@email":{"name":"acc name1","email":"email@email","password":"password1"}}
This is not correct.. How do I create a array in the format as above with the result of a mysqli statement?
$select = $mysqli->prepare("SELECT
name,
email,
password
FROM account
WHERE department = ? ");
$select ->bind_param("s", $department);
$select ->execute();
$data = [];
$result = $select ->get_result();
$accountdata = $result->fetch_all(MYSQLI_ASSOC);
foreach ($accountdata as $row) {
$data[] = [
'name' => $row["name"],
'email' => $row["email"]
];
echo json_encode(
[
$row["email"] => $row,
],
JSON_UNESCAPED_UNICODE
);
}
I am sorry for asking but is there anyone who can help me solve this?
CodePudding user response:
The problem is you're encoding each row of data as JSON separately, instead of waiting and encoding the whole structure at the end. That leads to a set of disparate, unconnected JSON objects, which aren't parseable as a coherent whole.
Here's a version which encodes a single object at the end of the process:
foreach ($accountdata as $row) {
$data[$row["email"]] = [
'name' => $row["name"],
'email' => $row["email"]
];
}
echo json_encode($data, JSON_UNESCAPED_UNICODE);
Demo: https://3v4l.org/4VYEg