Forum Moderators: coopster

Message Too Old, No Replies

Multi-dimensional Array Mixup when index is unset

Please help

         

neophyte

4:06 am on Jul 30, 2008 (gmt 0)

10+ Year Member



Hello All -

I've done a multi-dimensional "shopping-cart-type" Session array which is initially declared like this:

$_Session['CrewList'] => array
(
'Id' => array(),
'NameFirst' => array(),
'NameLast' => array(),
'Position' => array()
);

Values are added to each of the arrays like this:

'Id' = '123,456,789';
'NameFirst' = 'Scott,John,Sam'
'NameLast' = 'Johnson,Simson,Appleby'
'Position' = 'Painter,Carpenter,Laborer'

So far so good: I'm able to add the proper information to each array so that if I echo out index[0] (for example) from each array I would get:

ID 123
First Name Scott
Last Name Johnson
Position: Painter

Which is correct.

The aggravating problem is, that if I unset any index from each of the arrays via a loop, everything now gets mixed up: If I then re-echo index[0], I'll get something like this:

ID 456
First Name Scott
Last Name Simpson
Position Carpenter

Here's the code that I'm using to unset a specific key from this array:

$delKey = $_Get['del'];

foreach($_SESSION['CrewList'] as $k => $v)
{
unset($_SESSION['CrewList'][$k][$delKey]);

sort($_SESSION['CrewList'][$k]);
}

While trying to figure this problem out, I've read that you have to re-sort the array after deleting an index - which I have, but this doesn't seem to work... at least not for me!

Can someone else see the error of my ways (deadline is looming fast).

Appreciate all guidance!

Neophyte

MattAU

5:28 am on Jul 30, 2008 (gmt 0)

10+ Year Member



Using the sort function is definitely not what you want to do... That sorts the arrays alphabetically... :)

How to you access the indexes? Do you need them to be reset after deleting a key? If they do need to be reset you could look at using something like array_values.

foreach($_SESSION['CrewList'] as $k => $v)
{
unset($_SESSION['CrewList'][$k][$delKey]);

$_SESSION['CrewList'][$k] = array_values($_SESSION['CrewList'][$k]);
}

neophyte

8:02 am on Jul 30, 2008 (gmt 0)

10+ Year Member



MattAU -

You saved the day my friend. Works perfectly and I learned something valuable as well! Thank you very, very much!

Neophyte