Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

lukutisz's avatar

Need help in getting values from Collection

I have a multidimensional collection and cannot figure out how to get specific values from that collection.

The wanted result would be to extract price not for all of them, but only for specific Item->paymentTerm->prices

As example would be to get price for Item ID 'TEVELIAI' -> 'annual' -> 'guest' -> price, result should be 258.98

^ Illuminate\Support\Collection {#444 ▼ #items: array:2 [▼ 0 => App\Model\Accidents\Dto\AccidentsProductDto {#425 ▼ +id: "TEVELIAI" +paymentTerms: array:1 [▼ 0 => App\Model\Accidents\Dto\AccidentsPaymentTermDto {#424 ▼ +id: "annual" +prices: array:1 [▼ 0 => App\Model\Accidents\Dto\AccidentsPriceDto {#392 ▼ +priceType: "guest" +price: 258.98 } ] } ] } 1 => App\Model\Accidents\Dto\AccidentsProductDto {#422 ▼ +id: "SENELIAI" +paymentTerms: array:1 [▼ 0 => App\Model\Accidents\Dto\AccidentsPaymentTermDto {#407 ▼ +id: "annual" +prices: array:1 [▼ 0 => App\Model\Accidents\Dto\AccidentsPriceDto {#381 ▼ +priceType: "guest" +price: 162.55 } ] } ] } ] #escapeWhenCastingToString: false }

Maybe anyone of you could help with that or point in the right direction on how to get those values, thank you.

0 likes
6 replies
Sinnbeck's avatar

It is really hard to read.. What are we looking at?

My guess would be something like

$price = $collection->firstWhere('id', 'TEVELIAI')->paymentTerms->prices->price;

But I am unsure what is objects and what is arrays

lukutisz's avatar

@Sinnbeck I am sorry for readability, have attached an image. paymentTerms, prices are also arrays that has either id or priceType based on which we need to identify, so as each of these could have multiple values the provided method does not work.

Sinnbeck's avatar

@lukutisz Ok so perhaps something like this?

$price = $collection->firstWhere('id', 'TEVELIAI')->paymentTerms[0]->prices[0]->price;
1 like
lukutisz's avatar

@Sinnbeck Thank you, this returns the correct value, but if let's say we would have multiple paymentTerms and prices and ordering would change, it could return wrong values in this case, maybe any ideas how filter those two arrays the same way as the first item with firstWhere, I believe that would be the perfect solution to find based on their values.

Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

@lukutisz Break it up for readability

$product = $collection->firstWhere('id', 'TEVELIAI');
$term = collect($product->paymentTerms)->firstWhere('id', 'annual');
$price = collect($term->prices)->firstWhere('priceType', 'guest')->price;

Please or to participate in this conversation.