I'm really stuck and don't know how to tackle this: I'd like to query my MySQL database so I have a multidimensional associative Array of selected tables.
This array is my goal:
$ar = Array(
table1name=>Array(Array(field1=>a, field2=>b), Array(field1=>a, field2=>b)),
table2name=>Array(Array(field1=>a, field2=>b), Array(field1=>a, field2=>b)),
table3name=>Array(Array(field1=>a, field2=>b), Array(field1=>a, field2=>b)),
);
So if I encode it with json_encode($ar)
, the result should look like this:
{
"table1name": [
{
"field1": "a",
"field2": "b",
},
{
"field1": "c",
"field2": "d"
}
],
"table2name": [
{
"fieldx": "1",
"fieldy": "2",
},
{
"fieldx": "3",
"fieldy": "4"
}
],
"table3name": [
{
"fieldz": "1",
"fieldq": "2",
},
{
"fieldz": "3",
"fieldq": "4"
}
]
}
This is what I have so far but does not lead to expected results:
function tablesToJson()
{
$mysqli = new mysqli("localhost", "user", "password", "test");
$tables = Array();
array_push($tables, "table1name");
array_push($tables, "table2name");
$finalArray = Array();
foreach ($tables as $table) {
if ($result = $mysqli->query('SELECT * FROM ' . $table)) {
$rows = Array();
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
array_push($finalArray, $rows);
}
}
return $finalArray;
}