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.

3
  • Have a look at array_filter().It allows you to select the content of the resulting array by defining criteria (inside a callback function). Commented Mar 15, 2017 at 12:08
  • Look at this answer stackoverflow.com/a/4466437/4668162 Commented Mar 15, 2017 at 12:39
  • @Onix Look at answer of Ali Rasheed! It worked pretty well. It uses same logic and is simple Commented Mar 15, 2017 at 13:12

2 Answers 2

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)));
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.