Qmanchoo Qmanchoo - 1 month ago 9
PHP Question

Use php to parse two columns of data in a text file into a key value pair array

I'm a bit of a PHP noob. I have a text file with 10 comma separated pairs and I need to read them into a key=>value array.

3453453453,Bill Jones
...
...
3945845746,Joe Bob


Into this

Array
(
[3453453453] => Bill Jones
...
...
[3945845746] => Joe Bob
)


Here is my code so far

$people = array();
foreach(file('txtdatafinal') as $line)
{
list($key, $value) = explode(',' $line, 2);
$people[$key] = $value;
}
print_r($people);


However, even though the source file contains 10 rows, my code only gives 1 output array pair, which is always the last value in the text file.

Array
(
[3945845746] => Joe Bob
)


Even if I build two separate arrays, which will output all 10 unique values in two nice indexed arrays, and try to use array_combine I still only get the single output pair.

$people = array();
foreach(file('txtdatafinal') as $line)
{
list($key, $value) = explode(',' $line, 2);
$a[] = $key;
$b[] = $value;
}
$c = array_combine($a,$b);
print_r($c);

Array
(
[3945845746] => Joe Bob
)


My thinking is that the loop should be additive, but it seems to be replacing its key value pair each time. Can anyone help?

Answer

The output of file(...) is an array, that looks like:

Array 
(
    0 => number, name,
    1 => number, name,
    2 => number, name,
    ...
)

You have to explode $line = "number, name" in the foreach-loop:

$people = array();
$lines = file("file.txt");

foreach ($lines as $i => $line) {
    $line_arr = explode(",", $line);
    $people[$line_arr[0]] = $line_arr[1];
}

print_r($people);
Comments