我有这段代码:
<?php
set_time_limit(0);
ini_set('display_errors','On');
function ImportCSV2Array($filename)
{
$row = 0;
$col = 0;
$handle = @fopen($filename, "r");
if ($handle)
{
while (($row = fgetcsv($handle, 4096,";")) !== false)
{
if (empty($fields))
{
$fields = $row;
continue;
}
foreach ($row as $k=>$value)
{
$results[$col][$fields[$k]] = $value;
}
$col++;
unset($row);
}
if (!feof($handle))
{
echo "Error: unexpected fgets() failn";
}
fclose($handle);
}
return $results;
}
include_once("../config.php");
$nome_file = "./".$_GET['file'];
$csvArray = ImportCSV2Array($nome_file);
$i = 0;
foreach ($csvArray as $row=>$value)
{
$mp = array("1","2","3","4","5","7","11","12","13","16","17","18","26","27","28","33","34","42","43","45");
$fin = array("0","1","2","4","8","15","20","21","22","30","31","32","40","41","42","52","54","81","82","91");
$codEvento = str_replace($mp, $fin, trim($value['CODEV']));
if($value['INDEX']==0){
echo $codEvento."-".$value['CODEV'].";".$value['COGNNOME'].";".$value['TEMPO'].";".$value['ANNO'].";".$value['DATA']."<br>";
}
}
?>
当我尝试用str_replace转换$ fin数组中的$ mp数组时,我遇到了问题。
如果我的$ value ['CODEV']第一次包含“12”,它将替换为23,因为1被2和2替换为3.为什么它看到“12”字符串,这样我们两个不同的字符串?为什么它不能用“21”代替“12”?
答案 0 :(得分:1)
当您提供数组作为搜索&amp;将参数替换为str_replace
,它将遍历并用输入中相应的替换字符串替换每个找到的搜索字符串。
在你的情况下,&#34; 12&#34;是输入,所以它需要的第一个动作是替换&#34; 1&#34;使用&#34; 0&#34;,保留&#34; 02&#34;的值。接下来它找到&#34; 2&#34;并将其替换为&#34; 1&#34;给你一个值#34; 01&#34;。没有更多的匹配,所以你最终会得到&#34; 01&#34;。
如果您重新订购了搜索/替换对,那么&#34; 12&#34;显示在列表的前面,您仍然会得到错误的值。第一次搜索将取代&#34; 12&#34;用&#34; 21&#34; (你想要什么),但后来的传球会取代&#34; 1&#34;用&#34; 0&#34;和&#34; 2&#34;用&#34; 1&#34;离开你&#34; 10&#34;这一次。
问题是你的搜索字符串数组会自行处理。如果要完全替换输入字符串,那么循环可能会更好,如下所示:
$mp = array("1","2","3","4","5","7","11","12","13","16","17","18","26","27","28","33","34","42","43","45");
$fin = array("0","1","2","4","8","15","20","21","22","30","31","32","40","41","42","52","54","81","82","91");
$input = "12";
$output = "?";
for ($i=0; $i<count($mp); $i++) {
if ($input === $mp[$i]) {
$output = $fin[$i];
break;
}
}
echo $output