1

I have an array in session

array:7 [▼
  0 => array:2 [▼
    "store" => "store1"
    "product" => "1"
  ]
  1 => array:2 [▼
    "store" => "store2"
    "product" => "2"
  ]
  2 => array:2 [▼
    "store" => "store3"
    "product" => "4"
  ]
]

I made a function that to remove arrays that matches the value of store when given. for instance I give store1 it should remove store1 array and outputs like this

array:7 [▼
  0 => array:2 [▼
    "store" => "store2"
    "product" => "2"
  ]
  1 => array:2 [▼
    "store" => "store3"
    "product" => "4"
  ]
]

Instead I get the output

array:2 [▼
  1 => "store2"
  2 => "store3"
]

My function

function removeFromSessionArray($name, $value)
{
    return session()->put($name, array_diff(session()->get('stores'), [$value]));
}

Can someone tell how can me achieve the possible output?

PS. Learning arrays.

Alen
  • 1,221
  • 5
  • 21
  • 43
  • Have a look at [array_filter()](https://secure.php.net/manual/en/function.array-filter.php).It allows you to select the content of the resulting array by defining criteria (inside a callback function). – syck Mar 15 '17 at 12:08
  • Look at this answer http://stackoverflow.com/a/4466437/4668162 – Onix Mar 15 '17 at 12:39
  • @Onix Look at answer of Ali Rasheed! It worked pretty well. It uses same logic and is simple – Alen Mar 15 '17 at 13:12

2 Answers2

1

Try this

$m = session('products');
    for($i=0;$i<count($m);$i++)
    {
        if($m[$i]['store']==$username)
        {
            unset($m[$i]['store']);
            unset($m[$i]['product']);
        }
    }

    dd(array_values(array_filter($m)));
Ali Rasheed
  • 2,765
  • 2
  • 18
  • 31
0

You can use the simple index ([store value].[product value]) for this array, something like this:

array:7 [▼
  'store1.1' => array:2 [▼
    "store" => "store1"
    "product" => "1"
  ]
  'store2.2' => array:2 [▼
    "store" => "store2"
    "product" => "2"
  ]
  'store3.4' => array:2 [▼
    "store" => "store3"
    "product" => "4"
  ]
]

And after these changes you can simply delete any value from the session array