Array_merge() Question

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
I am writing a script to upload data to a delimited text file.  The
data is in the format:
recordID \t the rest of the data ...

It is significant that the recordID's are unique and that the newly
uploaded data replaces the old data in the event of duplicate

The solution I came up with (trying to avoid having to loop through
all of the records of both files looking for dupes) was to:
* treat both files as arrays using file()
* assign the keys of each line on each array using the alpha+recordID
  (prevents renumbering of key when ...)
* running array_merge ($old_data, $new_data)
* running ksort() on merged data to sort by recordID
* imploding the data on \n and writing to the data file

This seems to be working as planned.  However, I am really concerned
that the old data will not be overwritten by new when running

Comments, suggestions, snark, flames?  TIA!

The (simplified) code:

$data_file = "D:\pathto\data.txt";
$dfile = file($data_file);
$data_in = file(addslashes($_FILES['upload']['tmp_name']));
// I hate Windows servers!

foreach ($dfile as $line) {
 $line = trim($line);
 if (!empty($line)) { list ($id, $unused) = explode ("\t", $line); }
 $odata['a'.$id] = $line;

foreach ($data_in as $line) {
 $line = trim($line);
 if (!empty($line)) { list ($id, $unused) = explode ("\t",$line); }
 $ndata['a'.$id] = $line;

$mdata = array_merge ($odata, $ndata);

ksort ($mdata);

$fp = fopen ($data_file, 'w');
fwrite ($fp, implode("\n", $mdata));
fclose ($fp);  

Re: Array_merge() Question

Tyrone Slothrop wrote:
Quoted text here. Click to load it

Why aren't you using something like SQLite?

Andrew Hutchings - LinuxJedi -
Windows is the path to the darkside...Windows leads to Blue Screen. Blue  
Screen leads to downtime. Downtime leads to suffering...I sense much  
Windows in you...

Re: Array_merge() Question

Tyrone Slothrop wrote:
Quoted text here. Click to load it

I've looked into your problem and I think I can suggest simpler code


function merge($old, $new) {
    $new = str_replace("\t", "~\t", $new);
    $all = array_merge($old, $new);
    $all = implode("\n", $all);
    $all = preg_replace('/(\d+) .* \n ~ (.*)/x', "$1$2", $all);
    $all = str_replace('~', '', $all);
    return $all;


$a = array(
'1    bbb',
'2    ccc',
'7    vvv',
'5    zzz',

$b = array(
'3    XXX',
'2    CCCC',
'5    ZZZ',
'9    TTTT',

echo merge($a, $b);


Although I agree with Andrew you should use databases for this

gosha bine

extended php parser ~
blok ~

Site Timeline