Search code examples
phpmultidimensional-arrayphp-5.3

PHP: build an associative array from list without replacing values


I have this list in a file:

paul,1
peter,1
mary,1
ian,1
paul,2
peter,2
mary,2
paul,3
mary,3

I have to end up with an array like this:

$people=array(
    'paul'=>array(1,2,3),
    'peter'=>array(1,2),
    'mary'=>array(1,2,3),
    'ian'=>array(1)
);

Here is where I am:

$a=file($f);//$a=array, $f=file
foreach($a as $b){
    $l=explode(',',$b);//$l=list
    $p=$l[0];//$p=person
    $n=$l[1];//$n=number
}
print_r($lista);

But it is not working, of course. Any ideas?

Thanks.


Solution

  • You are nearly there, but you have to check your variable names. E.g. $d and $e are not defined anywhere and you are passing the wrong argument to in_array.

    This should do it:

    $file = file($f);
    $list = array();
    
    foreach($file as $line){
        list($name, $value) = explode(',', $line);
        if(!isset($list[$name])) {
            $list[$name] = array();
        }
        $list[$name][] = $value;
    }
    
    print_r($list);