简体   繁体   中英

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.

You are nearly there, but you have to check your variable names. Eg $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);

There is no requirement to check that an array already exists, or not, for the current name. PHP will, given the syntax below, happily create the array for a name if it does not already exist.

foreach ($a as $b) {
    list($name, $number) = explode(',', $b);
    $lista[$name][] = $number;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM