Reputation: 1291
I have an array session('products')
array:9 [▼
0 => array:2 [▼
"store" => "store1"
"product" => "1"
]
1 => array:2 [▼
"store" => "store1"
"product" => "11"
]
2 => array:2 [▼
"store" => "store2"
"product" => "5"
]
3 => array:2 [▼
"store" => "store3"
"product" => "6"
]
4 => array:2 [▼
"store" => "store5"
"product" => "16"
]
5 => array:2 [▼
"store" => "store5"
"product" => "18"
]
]
Now I have another array that is session('stores')
array:4 [▼
0 => "store1"
1 => "store2"
2 => "store3"
3 => "store5"
]
What I am trying to do is creating an session array dynamically and get the values from session('products')
that are matching that means.
Lets say I take first value from session('stores')
i.e 0=>"store1"
Now I will check the session('products')
for any Array that has store name as store1
to illustrate it output would be like this
session('store1')
array:4 [▼
0 => "1"
1 => "11"
]
session('store2')
array:4 [▼
0 => "5"
]
session('store3')
array:4 [▼
0 => "6"
]
session('store5')
array:4 [▼
0 => "16"
1 => "18"
]
What I tried
$full_array = session('products');
$stores = session('stores');
for($i=0; $i<=count($stores); $i++)
{
foreach($full_array as $arr)
{
//dd($stores[$i]);
//dd($arr['store']);
if($arr['store'] === $stores[$i])
{
session()->push($stores[$i], $arr['product']);
}
}
}
But it says Undefined offset: 4
. Can anyone help me with this problem?
Upvotes: 0
Views: 39
Reputation: 47894
I'm not a laravel dev, but this should safely perform the task without creating any unnecessary variables nor calling count()
on each outer loop iteration.
foreach(session('stores') as $i=>$store){
foreach(session('products') as $subarray){
if($subarray['store']===$store){
session()->push($store,$subarray['product']);
}
}
}
Upvotes: 1
Reputation: 18557
Try this,
$full_array = session('products');
$stores = session('stores');
for($i=0; $i<count($stores); $i++)
{
foreach($full_array as $arr)
{
//dd($stores[$i]);
//dd($arr['store']);
if($arr['store'] === $stores[$i])
{
session()->push($stores[$i], $arr['product']);
}
}
}
You need to change <= to <
so that its index will start from 0 and end before count of stores.
Upvotes: 0