簡體   English   中英

php txt 字符串比較 數組比較

[英]php txt string compare array compare

$c = '4432';
$word = file_get_contents('1234.txt');
$value = explode(" ",$word);
for ($i = 0; $i < 3; $i++) {
   if ($value[$i] = $c){
      echo $value[$i];
      break;
    }
}

文件1234.txt內容:

1234 789 
4432 998
5532 999

如何分別比較 4432 並得到值 789? 我需要:

if $c is 1234 then get 789 value
if $c is 4432 then get 998 value
if $c is 5532 then get 999 value

現在我的代碼只能得到 1234 或 4432 或 5532。

謝謝你。

您可以嘗試使用file()explode()函數獲得預期結果:

<?php
$match = '4432';

$file = file('1234.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($file as $line) {
    $words = explode(" ", $line);
    if ($words[0] == $match) {
        echo $words[1];
        break;
    }       
}
?>

補充說明:

  • Function file_get_contents()將整個文件讀入字符串,但file()將文件的內容返回到數組中。
  • PHP 中的比較運算符== ( === ),而不是=

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM