0
votes

Regarding this endpoint: https://shopify.dev/docs/admin-api/rest/reference/products/product#index-2020-04

I'm calling this with a comma separated list of IDs in the params. I assumed that the order of products returned by the API would be the same order as the comma separated list of IDs in the params. This doesn't seem to be the case.

Is there a way to have the order returned be the same?

If not, is there another way to do this after the fact?

Here is a snippet of my code:

        while($row = $result->fetch_array(MYSQLI_ASSOC)) {
            $productIDs[] = (int)$row['product_id'];
        }
        $params = array(
            'ids'        => implode(', ', $productIDs),
            'fields' => 'title,handle,vendor,price,images'
        );
        $products = $shopify->Product()->get($params);

The order of products in $products is not the same order as products in $productIDs.

Any idea why this is or how I can get the order to match?

2

2 Answers

0
votes

I ended up doing this:

            foreach($productIDs as $productID) {
                foreach($products as $product) {
                    if ($productID == $product['id']) {                 
                        $sortedProducts[] = $product;
                    }
                }
            }

Now $sortedProducts is essentially the $products variable sorted to match the order in $productIDs.

Is there a better way to do this than two nested loops?

0
votes

Here's another way to do that:

usort($products, function($p1, $p2) use ($productIDs) {
    $pos_p1 = array_search($p1['id'], $productIDs);
    $pos_p2 = array_search($p2['id'], $productIDs);
    return $pos_p1 - $pos_p2;
});

Shopify REST API doesn't support sorting products. I think products are always returned sorted by title.