2014-10-29 26 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 ";