2017-07-03 130 views
0

嘿所以我写这段代码来抓取csv列1,2,3中的数据,结果会输出第4列。对于现在可以正常工作,所以例如当前它显示列的所有输出4,但我怎么改变它从csv输出只显示1随机?随机输出csv的答案

if(!empty($inputs)) 
 
{ 
 
\t echo '<br><h4>Entity Type = <em>'.$inputs['eType'].'</em> <br> Entity Value = <em>'.$inputs['eVal'].'</em> <br> Intent = <em>'.$inputs['intent'].'</em></h4><br>'; 
 
\t $csv = array_map('str_getcsv', file('dialog.csv')); 
 

 
\t foreach($csv as $line){ 
 
\t  
 
\t  if($line[0] == $inputs['eType'] && $line[1] == $inputs['eVal'] && $line[2] == $inputs['intent']){ 
 
\t   echo "$line[3] <hr>"; 
 
\t  } 
 

 
\t } 
 
}

回答

0
if(!empty($inputs)) 
{ 
    echo '<br><h4>Entity Type = <em>'.$inputs['eType'].'</em> <br> Entity Value = <em>'.$inputs['eVal'].'</em> <br> Intent = <em>'.$inputs['intent'].'</em></h4><br>'; 
    $csv = array_map('str_getcsv', file('dialog.csv')); 

    $answers = []; 
    foreach($csv as $line){ 

     if($line[0] == $inputs['eType'] && $line[1] == $inputs['eVal'] && $line[2] == $inputs['intent']){ 
      $answers[] = $line[3]; 
     } 

    } 

    if ($count = count($answers)) 
     echo $count == 1 ? $answers[0] : $answers[mt_rand(1, $count) - 1] . " <hr>"; 
}