Показать первое значение в массиве

#laravel

Вопрос:

Я хочу показать первое значение только в массиве, где я использую самую низкую цену за сортировку.

Для отображения массива я использую return array_values, и он обычно работает, принося 3 значения, однако при использовании reset он приносит мне одно значение, но возврат не работает.

Код для получения только 1 значения.

 $arrays = array_values(
            collect($this->stores)
                ->filter(fn($store) => $store['active'])
                ->map(function($store) {
                    unset($store['margin']);
                    unset($store['refund']);

                    $store['price'] = ceil($store['price']);
                    $store['points'] = $this->hotsite->convertPoints($store['price']);

                    return $store;
                })
                ->sortBy('price')
                ->toArray()
        );

$first_value = reset(arrays);

return $first_value;
 

Код, который работает нормально, но отображает более одного значения.

 return array_values(
            collect($this->stores)
                ->filter(fn($store) => $store['active'])
                ->map(function($store) {
                    unset($store['margin']);
                    unset($store['refund']);

                    $store['price'] = ceil($store['price']);
                    $store['points'] = $this->hotsite->convertPoints($store['price']);

                    return $store;
                })
                ->sortBy('price')
                ->toArray()
        );
 

Метод toArray()

 public function toArray(): array
    {
        return [
            'id' => $this->id,
            'slug' => $this->slug,
            'name' => $this->name,
            'short_description' => $this->short_description,
            'details' => $this->details,
            'description' => $this->description,
            'information' => $this->information,
            'about' => $this->about,
            'validation_message' => $this->validation_message,
            'price' => $this->getPrice(),
            'points' => $this->getPoints(),
            'thumbnail' => $this->thumbnail? new ProductImage($this->thumbnail) : null,
            'images' => $this->getImages(),
            'soldOut' => $this->isSoldOut(),
            'stores'  => $this->getStores()
        ];
    }
 

Ответ №1:

Вы можете выполнить запрос напрямую, без необходимости получать все магазины, а затем фильтровать их.

Предполагая, что поле active является целым числом 1 или 0 и stores() является методом отношения.

 return ceil($this->stores()->where('active', '=', 1)->value('price'));
 

Комментарии:

1. Используя код, заданный из неопределенного метода.

2. @testCode как вы заполняете $this->stores ?

Ответ №2:

Я не знаю, требуется ли вам это для возврата массива, но вы можете извлечь первое значение из коллекции, которая у вас уже есть, используя этот first() метод.

 return   collect($this->stores)
                ->filter(fn($store) => $store['active'])
                ->map(function($store) {
                    unset($store['margin']);
                    unset($store['refund']);

                    $store['price'] = ceil($store['price']);
                    $store['points'] = $this->hotsite->convertPoints($store['price']);

                    return $store;
                })
                ->sortBy('price')
                ->first()
 

https://laravel.com/docs/8.x/collections#method-first

Комментарии:

1. toArray — это метод,я отредактировал сообщение, вставив метод в массив.