3

Is it possible to return entries in a random order through a Contentful Query?
Without specifying a "->where" parameter, it will sort the entries alphabetically.

I've tried using shuffle() and array_rand(), however it doesn't recognise a Contentful object as an array.

Here's what I currently have:

<?php   
$query = new \Contentful\Delivery\Query;
$query->setContentType(PRODUCT_TYPE);

$entries = $client->getEntries($q1->where('fields.images[exists]', 'true')->where('fields.category.sys.id', $entry->getCategory()->getId())->where('limit', '3'));

$array_shuffle = shuffle($entries)

foreach ($array_shuffle as $entry) 
  {}

?>
MarianD
  • 13,096
  • 12
  • 42
  • 54
thebfftim
  • 109
  • 1
  • 6

1 Answers1

2

Author of the Contentful PHP SDK here.

Unfortunately the class that holds the result from a query currently doesn't allow access to the internal array. I just opened a pull request to change that. It will be part of version 1.2, to be released later this week.

In the meantime your best bet is to use iterator_to_array().

<?php           
$query = new \Contentful\Delivery\Query;
$query->setContentType(PRODUCT_TYPE);

$entries = $client->getEntries($q1->where('fields.images[exists]', 'true')->where('fields.category.sys.id', $entry->getCategory()->getId())->where('limit', '3'));

$arrEntries = iterator_to_array($entries);

shuffle($arrEntries)

foreach ($arrEntries as $entry) 
  {}

Note I also fixed how shuffle() is used. It doesn't return the shuffled array, it changes it in place.

Rouven Weßling
  • 611
  • 4
  • 16