2014-01-18 110 views
1

我有兩個數組,它們檢查它們之間是否存在匹配,然後將yes插入到數據庫中,具體取決於匹配。其中一個數組每次需要3個元素,以便與靜態的其他元素進行比較。在數組中匹配字符串php

代碼中的問題是它正確地比較了大多數,但我仔細看了一下數據庫。幾個比較是不正確的。有沒有更好的方法來構建我的代碼,以便不正確地比較任何內容?

我發現錯過匹配發生時,$ team_squad中彼此相鄰的兩個元素都假設爲「是」。

該字符串也是非常正確的。

下面是代碼

<php 

//Take 3 subs at a time 3 home and 3 away players 
for($subs = 3;$subs<=$count_subs;$subs+=3){ 

//Set the answers for each player to 'no' (the for loop sets all players to no). 
for($data=0; $data<$squad_length; $data++){ 
    $input[$data] = 'no'; 
} 

//Select 3 subs home and away for each team, starting from 0 and restrict to 3 and move up by 3's. 
$h_subs_name = array_slice($home_subs_name,$subs-3, $subs); 
$a_subs_name = array_slice($away_subs_name,$subs-3, $subs); 

//Identify the matches from the players in the team squad with the subs 
$subshome = array_intersect($team_squad, $h_subs_name); 
$subsaway = array_intersect($team_squad, $a_subs_name); 

//if array is not empty run code 
if(!empty($subshome)){ 
//For each match in the change the 'no' to a 'yes' from the forloop. 
    foreach ($subshome as $key => $value) { 
    # code... 

    //Select the index to change to a yes 
     $input[$key] = $y; 

    } 
} 

//if array is not empty run code 
if(!empty($subsaway)){ 
//For each match in the change the 'no' to a 'yes' from the forloop. 
    foreach ($subsaway as $k => $eachplayer) { 
    # code... 

//Select the index to change to a yes 
     $input[$k] = $y; 
    } 
} 

foreach ($input as $s) { 
$inserttablesub[] = '"'. $s . '"'; 
} 

$querysub = 'INSERT INTO '.$subtable.' '.'('. implode(',', $players_name_insert).') '.'VALUES'.'(' . implode(',', $inserttablesub) . ')'; 

mysql_query($querysub) 
    or die(mysql_error()); 

unset($subshome); 
unset($subsaway); 
unset($input); 
unset($inserttablesub); 
} 

?> 

team_squad的簡單版本作爲列名在數據庫

回答

2

一個函數調用array_search,長相用於數組中的匹配並返回鍵號。

$key = array_search($a_subs_name[$c], $team_squad); 

這裏是文檔array_search

0

team_squada_subs_name應該是可變$team_squad$a_subs_name

您可以使用in_array()功能

編號:http://in3.php.net/in_array

+0

不,我試圖在數據庫的每個單元格中插入「是」或「否」。不只搜索一個元素 – user3210416

0

你爲什麼不嘗試array_interset()

這將找到2個陣列之間的常見的元素,你可以使用數組插入查詢」

$team_squad = array("Wojciech Szczesny", "Per Mertesacker","Olivier Giroud","Laurent Koscielny","Bacary Sagna","Mesut Özil","Aaron Ramsey","Kieran Gibbs","Santi Cazorla","Jack Wilshere","Bacary Sagna","Nacho Monreal","Thomas Vermaelen");  

$a_subs_name = array("Carl Jenkinson","Santi Cazorla","Lukas Podolski","Darren Bent","Alexander Kacaniklic","Giorgos Karagounis","Mathieu Flamini","Nacho Monreal","Bacary Sagna"); 

$result = array_intersect($team_squad, $a_subs_name); 
+0

看起來像這樣會工作,我會試試 – user3210416

+0

我認爲這將是一個好主意,但它似乎是爲我的數據的第一和第二行工作 – user3210416

+0

行?沒有得到它你能解釋一下嗎? –