So here is a small example of the query I play around with:

$db->setQuery('SELECT position, title FROM jos_modules
SELECT position, title FROM jos_modules
$data= $db->loadAssocList();

This returns all modules.

It does not matter if this does not make sense. It's just an example of a more complex query. The UNION approach is a must in the original query.

But i need the data indexed on a key like this:

$data= $db->loadAssocList('position');

If doing that, not all modules are returned. So it seems the indexing only catches the first result.

Can such a UNION query be done and results returned indexed on a key?

2 Answers 2


No, there's no such option. You have to do it yourself:

$data = [];

foreach ($db->loadAssocList() as $row)
    $data[$row['position']][] = $row;

The OP actually works as it should. The actual query that has been posted UNIONs the data with itself, so the records in both sets have the same keys. Only one set of data is returned because the first set is overwritten by the second set. The same issue would be seen in @Sharky's answer.

If you change the query to have different data sets:

$db->setQuery('SELECT position, title FROM #__modules UNION (SELECT id AS position, title FROM #__content)');
$data = $db->loadAssocList('position');

then both sets of data appear in the result:

array(121) {
  array(2) {
    string(10) "position-7"
    string(10) "Login Form"
  array(2) {
    string(5) "login"
    string(5) "Login"
  array(2) {
    string(3) "202"
    string(14) "Example article 1"
  array(2) {
    string(3) "203"
    string(24) "Example article 2"
  • Thanks but selecting from different tables was not the question. I need to select from the same table.
    – maidan
    Jun 13, 2023 at 15:34
  • I'm sorry for misinterpreting your question. I must've been tired when I answered it because now it's clear that you want the results indexed on a non-unique field and so my answer was not going to achieve what you wanted. My apologies to @Sharky, as his answer does indeed seem the simplest solution to what you need. Jun 13, 2023 at 22:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.