0

2つの異なるテキストファイルから2つの異なる数値を取得し、それらを1つの変数に入れて、MYSQL配列と比較しようとしています。私の問題は、次のような3つの変数を定義するときです。

$num = 42;

$whichPlaylist = 2;

$joint = "$whichPlaylist $num"

アレイでテストすると、機能します。ただし、テキストファイルから2と42を取得すると、機能しません。$ trimを使用してみましたが、修正されていないようです。変数を定義すると機能するのに、テキストファイルから取得すると機能しないのはなぜですか?それらはまったく同じものです(ただし、テキストファイルには改行があります)。

これが私のコードです:

//Connect to DB
$config = array(
'host'       => 'localhost',
'username'   => '******',
'password'   => '******',
'dbname'     => '******'
);

$db = new PDO('mysql:host='.$config['host'].';dbname='.$config['dbname'],$config['username'],$config['password']);
$query = $db->query("SELECT `recentlyplayed`.`numplayed`, `recentlyplayed`.`id` FROM `recentlyplayed`");


//Put numbers from text files into variables
$num = file_get_contents('/home/*****/num.txt'); // has the value "42" with new line
$whichPlaylist = file_get_contents('/home/*****/whichplaylist.txt'); // has the value "2" with newline
$playlist3_num = file_get_contents('/home/*****/playlist3_num.txt');





//$whichPlaylist = 2;
//$num = 42;
$joint = "$whichPlaylist $num";
$trimmed = trim("$joint");
echo $trimmed;


while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
if (in_array($trimmed, $row)){
    echo " In Array!"; //This does NOT work, but if I use the self-defined variables $whichPlaylist and $num (and comment out file_get_content variables) it DOES work.

}

}
4

2 に答える 2

6

変数を結合する前に、file_get_contentsから変数をトリミングする必要があります。それ以外の場合、改行は結果の文字列に含まれます。トリミングでは、文字列の最初と最後から空白のみが取得され、これにより文字列が中央に配置されます。

于 2013-01-10T00:32:40.950 に答える
1

値を結合する前に、値をトリミングする必要があります。そのような:

$num = trim(file_get_contents('/home/*****/num.txt')); // has the value "42" with new line
$whichPlaylist = trim(file_get_contents('/home/*****/whichplaylist.txt')); // has the value "2" with newline
$playlist3_num = file_get_contents('/home/*****/playlist3_num.txt');

$joint = "$whichPlaylist $num";
于 2013-01-10T00:33:56.830 に答える