Something like this?
$words = array(
'word1' => array(
'meaning' => 'word1 meaning',
'synonyms' => array(
'word1 synonym1',
'word1 synonym2'
),
'antonyms' => array(
'word1 antonym1',
'word1 antonym2'
)
),
'word2' => array(
'meaning' => 'word2 meaning',
'synonyms' => array(
'word2 synonym1',
'word2 synonym2'
),
'antonyms' => array(
'word2 antonym1',
'word2 antonym2'
)
)
);
If this is what you're looking for, it is pretty straightforward to create such an array dynamically from whatever datasource you have available. Since you haven't provided that information in your question, let's assume you have a MySQL database that's structured like this:
+----------+
+---------+ | synonyms |
| words | +----------+
+---------+ | id |
| id | -+-> | word_id |
| word | | | synonym |
| meaning | | +----------+
+---------+ |
| +----------+
| | antonyms |
| +----------+
| | id |
\-> | word_id |
| antonym |
+----------+
This is of course very simplistic, you'll have a lot of duplicates in the synonyms
and antonyms
table with this configuration.
You can use standard PDO
or mysqli
functionality to retrieve the information from your database. Since it's not clear whether your datasource is in fact a MySQL-database, I'm going to assume mysqli
and use very basic queries in this example. After all, the purpose here is not to teach you how to communicate with your database securely, but how to build a multidimensional array you can pass through json_encode()
. Here's one way you can do that:
$words = array();
$mysqli = new mysqli(...);
// retrieve the list of words from the `words` table
$words_res = $mysqli->query('SELECT * FROM `words`');
while ($word = $words_res->fetch_assoc()) {
// build the initial sub-array for this word, we'll be adding
// it to $words after we fill it
$word_array = array(
'meaning' => $word['meaning'],
'synonyms' => array(),
'antonyms' => array()
);
// retrieve all synonyms for this word
$synonyms_res = $mysqli->query('SELECT * FROM `synonyms` WHERE `word_id` = ' . $word['id']);
while ($synonym = $synonyms_res->fetch_assoc()) {
// add this synonym to our $word_array
$word_array['synonyms'][] = $synonym['synonym'];
}
// retrieve all antonyms for this word
$antonyms_res = $mysqli->query('SELECT * FROM `antonyms` WHERE `word_id` = ' . $word['id']);
while ($antonym = $antonyms_res->fetch_assoc()) {
// add this antonym to our $word_array
$word_array['antonyms'][] = $antonym['antonym'];
}
// now that $word_array is filled, we can add it to $words
$words[$word['word']] = $word_array;
}
// since you say you want a JSON result, convert the array to
// JSON and output it
echo json_encode($words);