First of all, the last time I did php was 10 years ago in school, so I'm basically a noob :D

I have two channels, let's say shops and products. Shops contains a matrix field composed of a product entry field and a price field to make an ultra simple pivot table like behavior (like proposed in a previous question), so I can have shops linked to products with a specific price per shop.

I made a controller to have a custom api endpoint with a basket parameter, where multiple users can select products in a vue frontend. The goal is to calculate per shop the price of all products for all users and sort it.

It works the way I did it, but there is a lot of room for optimisation.

Here is my code, keep in mind that the business case here is fake to simplify the code;

public function actionResults($basket): String

    $shops = Entry::find()->section('shops')->all();
    $profile = json_decode($basket);
    $results = [];

    foreach ($shops as $shop)
        // basket contains users that contains the selected products
        $price = $this->calculatePrice($shop, $basket->users);
        // fill $results array with total price and other fields to be sent back

    usort($results, function($a, $b) {
        if ($a->totalPrice == $b->totalPrice)
            return 0;
        else if ($a->totalPrice > $b->totalPrice)
            return -1;
        else {
            return 1;

    return Json::encode($results);

private function calculatePrice($shop, $users)
    $totalPrice = 0;

    foreach ($users as $user){
        foreach ($user->products as $userProduct){
            $product = NULL;
            // search a corresponding matrix row
            foreach ($shop->products->all() as $shopProduct) {
                // have to get the entry to access the slug and other fields (I work with slugs 
                in the front)
                $shopProductEntry = $shopProduct->product->one();
                if ($shopProductEntry->slug == $userProduct->slug) {
                    $product = $shopProduct;
                    $product->shopProduct = $shopProductEntry;

            if ($procut)
                 $totalPrice += $product->price;

    return $totalPrice;

What do you think about this ? Kind of crap right ? I have like 40 shops and 10 products for few users and it takes one to two seconds to get a response with 0 load on the server since the website is not public yet.

Thanks for reading me,


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.