Merging query results

I am curious how I might merge two or more query results. Or even more specific (If possible) how I could convert the response into an associative array, run array functions on it and convert it back to a form that contentful delivery API still works on it.

Example of intent: Query for featured products and then randomize the results, then merge a query of products that are not featured.

This seems like I would have to use json_encode/decode, and shuffle($array). Is this possible? I haven’t been able to do it.

If it isn’t possible, is there a way to take 2 query results and combine them without array manipulation?

Any help is appreciated.

Hey bdkruse80,

what you’re asking is a bit contrived, so there is some manual glueing you will definitely need to do, but it’s possible.

First of all, you can call $entries->getItems() which will give you a regular array containing SDK resource objects, which you’ll still be able to use as you’d do normally. This way you’d have an array which you’d be able to shuffle() and do regular array operations, without sacrificing SDK features (like automatic link resolution in entries, for instance).


If you need something more complex (but also a bit more difficult), read this: as a starting point, SDK resource objects (entries, assets, resource arrays etc) can be serialized as JSON because they implement the \JsonSerializable interface. An use which would be a bit unorthodox but would probably work for you would be to manually call $array = $entries->jsonSerialize() (with $entries being an instance of Contentful\ResourceArray that you received from $client->getEntries()), so you have a plain PHP array that you can manipulate however you want (actual results will be in $array['items'], just like they are in the API responses).

After you’re done with the manipulation, you will need to encode your result as a JSON string that is parsable from the client (so basically, one which has the same structure as a normal API query), and pass that string to $client->reviveJson($json), which will convert your string back to regular SDK objects. As I said, this use case is a bit more fragile, but if you have extremely specific needs, it might be worth giving it a shot.

Hope this helps,

Davide