2014-10-29 50 views
0

输入我有这样的代码:检查是否阵列是相同的,从textarea的

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="utf-8"> 
    <title>Frans</title> 
</head> 
<body> 
    <form method="POST"> 
<textarea name="textarea" cols="16" rows="4" wrap="OFF"/> 
</textarea><input type="submit" name="submit" value="submit"> 
</form><pre><?php 
if(isset($_POST['submit'])){ 
if(!empty($_POST['textarea'])) { 

    $exp = array_filter(explode("\n", $_POST['textarea'])); 

    print_r($exp); 

    // Add DB Insert here 
} 
$correct = array(
'Beau', 
'Haut', 
'Jeune', 
'Gros', 
'Nouveau', 
'Bon', 
'Long', 
'Vieux', 
'Mauvais', 
'Autre', 
'Joli', 
'Petit', 
'Grand', 
'Large', 
'Premier', 
'Cher', 
); 

$input = $_POST['textarea']; 

echo ($correct == $input) ? 'they\'re same' : 'they\'re different'; 
print_r($correct); 
} 
?> 

</body> 
</html> 

我basicly要检查,如果该阵列是相同的,从textarea的输入。这是输入应该是什么:

雪儿 博 浩 热恩 格罗斯 风格 苯教 龙 老 MAUVAIS 其它物业 阿邦 佩蒂特 大 大 总理

输出结果应该是:重新相同。 但我做错了,因为它一直说:“他们不同” 在此先感谢。

输入错了,请原谅。 编辑:

博 浩 热恩 格罗斯 风格 苯教 龙 老 MAUVAIS 其它物业 阿邦 佩蒂特 大 大 总理 雪儿

+1

参见http://stackoverflow.com/questions/901815/php-compare-array – aland 2014-10-29 20:19:40

+1

'$输入= $ _POST [ 'textarea的']'是一个字符串,而不是阵列。我想你想比较'$ correct'和'$ exp'来代替。 – showdev 2014-10-29 20:20:21

回答

1

你的阵列有不同内部排序,这意味着他们是不同的。两个数组将只测试相等如果他们有相同数量的元素,以相同的顺序,以相同的值:

php > $x = array('a', 'b'); 
php > $y = array('b', 'a'); 
php > $z = array('a', 'b'); 

php > var_dump($x == $y); 
bool(false) 

php > var_dump($x == $z); 
bool(true) 

尝试运行均通过sort(),这样(理论上),他们都在相同的顺序。

+0

对不起,他们应该按照需要的输入顺序排列。我的错。 – MrDikke 2014-10-29 20:23:37

+0

textarea只是提交为单个字符串,而不是数组,因此替换/折叠该字符串中的任何换行符,用一个空格implode您的其他数组,然后比较字符串。 – 2014-10-29 20:25:05

0

使用in_array - http://php.net/manual/en/function.in-array.php

遍历您的阵列;

$exp = explode("/n", $_POST['textarea']); 

for ($i = 0; $i < count($exp); $i++) 
{ 
    if (in_array($exp[$i], $correct)) 
    { 
    $output = "They're the same"; 
    } 
    else 
    { 
    $output = "They're different"; 
    break; 
    } 
} 

echo $output; 
0
if (count ($array1) == count ($array2) ) //have same size 
{ 


$identical = 1; //we assume both are identical and some item is different will become 0 

for ($i=0; $i <count ($array1) ; i++) 
{ 

if ($array1[$i] != $array2[$i]) 
    $identical = 0; 

} 

if ($identical == 1) 
    echo "arra1 is identical with array2 ,all items is same order"; 
else 
    echo "arra1 is different form array2 "; 

} 
else 
    echo "arra1 is diffeent form array2 ";