I take a number of rows from the MySQL table:

$IDs = array(5,3,1,4,2); $db = JFactory::getDBO(); $query = $db->getQuery(true); $query->select($db->quoteName(array('id','introtext'))) ->from($db->quoteName('#__content')) ->where($db->quoteName('id')." IN (".implode(',', $IDs).")"); $db->setQuery($query); $articles = $db->loadObjectList(); 

And I bring it on the site through:

 foreach($articles as $article) { echo $article->introtext; } 

But everything is displayed NOT according to the order of the $ IDs array, i.e. First the object with ID 5, then 3, etc. but in ascending order i.e. 1, 2, 3, 4, 5.

How to make everything output according to the $ IDs array?

ps. Joomla API Syntax

  • You can use ORDER BY FIELD(id, " . implode(',', $IDs) . ") (I don’t know how it will be correct in PHP and Joomla), but it is quite possible (to check) which is better in terms of performance will sort in the php code. - Regent
  • And how to sort in the PHP code? - stckvrw
  • Save the resulting lines in the form of a hash table (for sure, there is such a thing in PHP), the key in which will be the ID of the received string, and the value will be the string itself. Then in a loop, go over $IDs and take the corresponding article from the hash table. - Regent

2 answers 2

First, create an array with the necessary sorting and then output to the page

 // ΠŸΠ΅Ρ€Π΅ΡΡ‚Ρ€Π°ΠΈΠ²Π°Π΅ΠΌ индСксы исходного массива $IDs = array_merge($IDs); // Π€ΠΎΡ€ΠΌΠΈΡ€ΡƒΠ΅ΠΌ массив ΠΈΠ· null элСмСнтов ΠΈ Π΄Π»ΠΈΠ½ΠΎΠΉ исходного массива $content = array_fill(0, count($IDs), null); foreach($articles as $article) { // заполняСм массив Π² Π½ΡƒΠΆΠ½ΠΎΠΌ порядкС $content[array_search($article->id), $IDs] = $article->introtext; } // Π²Ρ‹Π²ΠΎΠ΄ΠΈΠΌ всС Π·Π°ΠΏΠΎΠ»Π½Π΅Π½Π½Ρ‹Π΅ значСния foreach($content as $article) { if (isset($article)) echo $article; } 

    I found myself a similar option, but it seems to be simpler:

     $arrayOfArticles = array(); foreach($articles as $unsortedArticle) { $arrayOfArticles[$unsortedArticle->id] = $unsortedArticle; } foreach($IDs as $sortedID) { $article = $arrayOfArticles[$sortedID]; echo $article->introtext; } 
    • This is just the option that I described. - Regent