Issue
Is it possible to customize the index of array in Laravel Builder?
I need the index is not incremented from 0 but with some integer
This is my code:
foreach ($members as $member) {
$check[$member->id] = TransactionInNon::where('member_id', $member->id)
->whereYear('created_at', $year)
->orderBy('date', 'ASC')
->limit(12)
->get()
->toArray();
}
I need the index of array can be customizable like
7 => array:11
10 => array:11
instead of
0 => array:11
1 => array:11
Solution
It is possible with mapWithKeys method in laravel collection. For to show result you may change script like this:
#start from
$i = 33;
foreach ($members as $member) {
$check[$member->id] = TransactionInNon::where('member_id', $member->id)
->whereYear('created_at', $year)
->orderBy('date', 'ASC')
->limit(12)
->get()
->mapWithKeys(function($item,$key) use (&$i) {
$i++;
return [$i => $item];
})
->toArray();
# if you want to set $i like old content
$i = 33;
}
Answered By – Tural Rzaxanov
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0