Andrew
Andrew

Reputation: 7768

Creating a multi-dimensional json based on mysql query

Earlier, I used to encode the result set (one dimensional) into json. Now, I need to create a multi-dimensional json data structure based on multiple tables. I never done this and I need some help.

My tables:

I need to develop JSON response that has this structure for each row:

How should I do it?

For example, I am thinking that I can create 3 queries for each table (phones, addresses, names) and return a data set for each table and then encode each result set into json. Now my questions: Will it be a correct way of doing this? How do I add each child json into my parent json?

$userJson = json_encode($user_id_resultSet);
$phonesJson = json_encode($phones_resultSet);
$addressesJson = json_encode($addresses_resultSet);
$namesJson = json_encode($names_resultSet);
//how do I combine them into one row?

Upvotes: 1

Views: 1208

Answers (1)

Axel Amthor
Axel Amthor

Reputation: 11096

$combined = array(
  "user" => $user_id_resultSet,
  "phones" => $phones_resultSet,
  "addresses" => $addresses_resultSet,
  "names" => $names_resultSet
);

echo json_encode($combined, JSON_PRETTY_PRINT); // just for neat output.

Upvotes: 2

Related Questions