Thursday, March 9, 2017

selecting items from a given session array and store it in other session array in laravel

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

OUTPUT

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?



via Alen

Advertisement