user7175325
user7175325

Reputation:

How to get a specific array inside laravel collection

I do have the collection below:

Collection {#265 ▼
  #items: array:3 [▼
    0 => array:9 [▼
      "dueDate" => "2017-10-29"
      "date" => "2017-09-29"
      "number" => "9030001"
      "statuse" => "Reminder"
      "currentCode" => "S"
      "amount" => 2006.0
      "remainingAmount" => 2006.0
      "convertedToAccountNumber" => null
      "originalCreditorReference" => "0903"
    ]
    1 => array:9 [▼
      "dueDate" => "2017-10-29"
      "date" => "2017-09-29"
      "number" => "9030022"
      "statuse" => "Reminder"
      "currentCode" => "S"
      "amount" => 2294.0
      "remainingAmount" => 2294.0
      "convertedToAccountNumber" => null
      "originalCreditorReference" => "0903"
    ]
    2 => array:9 [▼
      "dueDate" => "2017-11-01"
      "date" => "2017-10-02"
      "number" => "9040023"
      "statuse" => "Unpaid"
      "currentCode" => "S"
      "amount" => 3643.0
      "remainingAmount" => 3643.0
      "convertedToAccountNumber" => null
      "originalCreditorReference" => "0904"
    ]
  ]
}

My question is except iterating with a foreach loop is there any way getting a specific array inside this collection based on number key example I want to get back the array where number is equal to 9040023?

note. I did it using a foreach but I want to use laravel collection instead.

Upvotes: 0

Views: 1945

Answers (2)

umuttaymaz
umuttaymaz

Reputation: 134

You can use collection Helper Method (also Eloquent) : flatMap

The flatMap method iterates through the collection and passes each value to the given callback. The callback is free to modify the item and return it, thus forming a new collection of modified items. Then, the array is flattened by a level (using collapse() collection method).

$collection->flatMap(function ($item){
    if ($item['number'] === "9040023"){
        return $item;
    }
});

Upvotes: 0

Hedegare
Hedegare

Reputation: 2047

You can use the where method:

$collection->where('number', 9040023)->all();

Upvotes: 1

Related Questions