简体   繁体   中英

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') ie 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?

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']);
        }
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM