假设我想包含 2 个这样的文本文件(变量是路径):
<?php
include($ingredientsFirst);
include($ingredientsSecond);
?>
$ingredientsFirst (.txt-file):
1 Banana<br>
2 Apples<br>
$ingredientsSecond (.txt-file):
3 Banana<br>
4 Apples<br>
有没有一个函数可以总结两个不同文件中的这些成分,然后像这样输出它们:
4 Banana<br>
6 Apples<br>
提前谢谢。
没有内置任何东西,但我认为你可以用一些数组来处理这个问题。我会用成分作为关键,数量作为价值。例如像这样:
<?php
function combine_ingredients($files_array)
{
$res = array();
foreach( $file_array as $file ){
//Open each file
$file_r = fopen($file, 'r');
while( ($line = fgets($file_r)) !== FALSE ){
$parts = explode(' ', $line);
//Grab the number of an ingredients
$quantity = intval(array_shift($parts));
$key = implode(" ", $parts);
//Have I seen this ingredient already
if( isset($res[$key]) )
$res[$key] += $quantity;
else
$res[$key] = $quantity;
}
//Close the file
fclose($file_r);
}
return $res;
}
print_r( combine_ingredients(array($ingredientsFirst, $ingredientsSecond)) );
数据不一致可能会有很多错误,但这是一个很好的起点。