You are here:  » Limit results from the array


Limit results from the array

Submitted by formmailer on Sat, 2007-10-20 06:52 in

Hi David,

I've managed to shuffle the array like you said in: http://www.magicparser.com/node/558

This works fine, but how can I limit the number of result being displayed from the array.
Right now I used a foreach, but this is, of course, wrong.
Can you help me out?

My current code is:

<?php
  
require("MagicParser.php");
  
$records = array(); // global array of records to pick from later
  
function myRecordHandler($record)
  {
    global 
$records;
    
$records[] = $record;
  }
  
MagicParser_parse("productfeed.xml","myRecordHandler");
  
shuffle($records);
  
// now you pick off as many random records as you require....
  
foreach ($records as $record) {
  print 
$record["NAME"];
  print 
$record["PRICE"];
  print 
$record["PRICE-CURRENCY"];
  print 
$record["PRODUCTURL"];
  print 
$record["IMAGEURL"];
  }
?>

Thanks!

/Jasper

Submitted by support on Sat, 2007-10-20 08:08

Hi Jasper,

The most efficient way to do this, which doesn't involve copying the array around in memory is to do this:

  $count = 0;
  foreach ($records as $record) {
  print $record["NAME"];
  print $record["PRICE"];
  print $record["PRICE-CURRENCY"];
  print $record["PRODUCTURL"];
  print $record["IMAGEURL"];
  $count++;
  if ($count == 5) break;
  }

Simply change the value of 5 as required...

Cheers,
David.

Submitted by formmailer on Sat, 2007-10-20 09:18

Wow David, you are really fast regarding support!
Thanks for this easy trick! :-)

/Jasper