user1216398
user1216398

Reputation: 1960

PHP can I do a hash of arrays?

I'm currently trying to create a hash table of arrays like so:

joe
   => 1
   => 2
pete
   => 1
   => 3

My PHP code looks like this:

$name = array(); 

while(my condition statement) { 
    if (preg_match("/(.+?)\s*\-\s*(.+?)/", $info)) {                

        list($name, $number) = split('\s*\-\s*', $info);                
        array_push($name,$number);

    }
}

$_SESSION['info'] = $name;

My outout looks like this:

[0] => 1 [1] => 2

Why is the name not showing up?

I know in Perl I've always done something like this:

while() {
    push @{$hash{$name}}, $number
}

Upvotes: 1

Views: 790

Answers (2)

webbiedave
webbiedave

Reputation: 48887

$names = array(); 

// [...]

list($name, $number) = split('\s*\-\s*', $info);
$names[$name][] = $number;

Upvotes: 1

Niko Sams
Niko Sams

Reputation: 4414

correctly specify the index:

$array['joe'][] = 1;
$array['joe'][] = 2;
$array['pete'][] = 1;
...

in your example something like:

$array[$name][] = $number;

though I don't really get your code as you overwrite $name in the while loop.

Upvotes: 2

Related Questions