2017-07-03 9 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>"; 
} 
関連する問題