PHP in_array使用文本文件中的值不起作用

时间:2013-01-10 00:27:33

标签: php mysql arrays pdo

我正在尝试从两个不同的文本文件中获取两个不同的数字,将它们放入一个变量中,并将其与MYSQL数组进行比较。我的问题是,当我定义三个变量时:

$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.

}

}

2 个答案:

答案 0 :(得分:6)

在加入变量之前,你需要修改file_get_contents中的变量;否则换行符将出现在结果字符串中。修剪只从字符串的开头和结尾取空格,这会把它放在中间。

答案 1 :(得分: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";