-2

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.

anaszaman
  • 297
  • 6
  • 19
  • above code is showing all contents. I want to show only four of them randomly – anaszaman Jul 18 '14 at 10:52
  • 1
    I suggest to start by reading http://php.net/manual/en/. In your case http://php.net/manual/en/book.array.php can be particularly interesting. – Mike Jul 18 '14 at 11:01
  • 2
    Don't add a comment to further explain your question. Just edit the question. – Mike Jul 18 '14 at 11:04

1 Answers1

0

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);
}
thedom
  • 2,498
  • 20
  • 26