Search code examples
phprandomarticle

how to show random articles


I am working on project which shows articles and this was done by article manager (a ready to use php script) but I have a problem, I want to show only four article titles and summaries from old list of article randomly which contains 10 article. Any idea how to achieve this process? I have auto generated summary of article

<div class="a1">
<h3><a href={article_url}>{subject}</h3>    
<p>{summary}<p></a>
</div> 

When a new article is added the above code will generated and add into summary page. I want to add it to side of the main article page, where user can see only four article out of ten or more randomly.

<?php
$lines = file_get_contents('article_summary.html');
$input = array($lines);
$rand_keys = array_rand($input, 4);
echo $input[$rand_keys[0]] . "<br/>";
echo $input[$rand_keys[1]] . "<br/>";
echo $input[$rand_keys[2]] . "<br/>";
echo $input[$rand_keys[3]] . "<br/>";
?>

Thanks for your kindness.


Solution

  • Assuming I understood you correctly - a simple solution.

    <?php
    // Settings.
    $articleSummariesLines = file('article_summary.html', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $showSummaries = 4;
    
    // Check if given file is valid.
    $validFile = ((count($articleSummariesLines) % 4 == 0) ? true : false);
    if(!$validFile) {
      die('Invalid file...');
    }
    
    // Count articles and check wether all those articles exist.
    $countArticleSummaries = count($articleSummariesLines) / 4;
    if($showSummaries > $countArticleSummaries) {
      die('Can not display '. $showSummaries .' summaries. Only '. $countArticleSummaries .' available.');
    }
    
    // Generate random article indices.
    $articleIndices = array();
    while(true) {
      if(count($articleIndices) < $showSummaries) {
        $random = mt_rand(0, $countArticleSummaries - 1);
    
        if(!in_array($random, $articleIndices)) {
          $articleIndices[] = $random;
        }
      } else {
        break;
      }
    }
    
    // Display items.
    for($i = 0; $i < $showSummaries; ++$i) {
      $currentArticleId = $articleIndices[$i];
    
      $content = '';
      for($j = 0; $j < 4; ++$j) {
        $content .= $articleSummariesLines[$currentArticleId * 4 + $j];
      }
    
      echo($content);
    }