29-08-2016, 19:37
|
מנהל פורומי "תכנות ובניית אתרים" ו"חומרה ורשתות"
|
|
חבר מתאריך: 25.10.01
הודעות: 42,775
|
|
האם סדר השורות בקובץ משנה? או שמה שחשוב הוא עדכניות הנתונים בהתאם לסדר הקריאה של הקבצים שאותם ממזגים? (שהרי הקשר הוא ממילא חח"ע, על פניו סדר האחסון בקובץ לא אמור לשנות)
אם הסדר לא משנה, הפתרון הטריוויאלי:
קוד PHP:
<?php
$files_to_merge = array('b1.txt', 'b2.txt');
$key_column_id = 1; # set this to the ordinal location of the key which gets updated
$out = array();
foreach($files_to_merge as $file) {
$in = file_get_contents($file);
if (!$in) {
echo "Error opening/reading $file (or file is empty). Aborting!\n";
exit(1);
}
foreach(explode("\n", $in) as $line) {
$line = trim($line);
if (strlen($line)) {
$splitted = explode(' ', $line);
$out[$splitted[$key_column_id-1]] = $line;
}
}
}
echo "Merged file:\n\n";
echo implode("\n", $out);
echo "\n";
?>
(אגב, אפשר לתת רשימה של מספר לא מוגבל של קבצים...)
אם אתה בהכרח רוצה להתחיל דווקא מהאחרון ולהכניס לתוכו שורות נוספות שהמפתח החח"ע שלהן לא היה קודם (ואז בעצם המיון יהיה לפי סדר ההופעה בטעינת הקבצים מהמעודכן ביותר לישן ביותר), אפשר כך:
קוד PHP:
<?php
$files_to_merge = array('b1.txt', 'b2.txt');
$key_column_id = 1; # set this to the ordinal location of the key which gets updated
$out = array();
$files_to_merge = array_reverse($files_to_merge);
foreach($files_to_merge as $file) {
$in = file_get_contents($file);
if (!$in) {
echo "Error opening/reading $file (or file is empty). Aborting!\n";
exit(1);
}
foreach(explode("\n", $in) as $line) {
$line = trim($line);
if (strlen($line)) {
$splitted = explode(' ', $line);
if (!array_key_exists($splitted[$key_column_id-1], $out)) {
$out[$splitted[$key_column_id-1]] = $line;
}
}
}
}
echo "Merged file:\n\n";
echo implode("\n", $out);
echo "\n";
?>
בתקווה שהבנתי את הדרישות שלך נכון...
|