2017-09-11 32 views
-1

我想用數組替換SQL表中所有可用的文本,但我不知道如何實現它。我成功讓所有的結果,但我無法在str_replace函數使用它()函數PHP/MySQL數組替換函數不起作用

這裏是我的陣列

Array 
(
    [0] => Array 
     (
      [txtSearch] => fruits 
      [txtReplace] => pizza 
     ) 

    [1] => Array 
     (
      [txtSearch] => vegetables 
      [txtReplace] => beer 
     ) 

    [2] => Array 
     (
      [txtSearch] => fiber 
      [txtReplace] => ice cream 
     ) 

) 

這是我的PHP代碼

include('site-primary-config.php'); 
$select="SELECT txtSearch, txtReplace FROM tblreplacements"; 
$result = $conn->query($select) or die($conn->error.__LINE__); 

$arr = array(); 
if($result->num_rows > 0) { 
    while($row = $result->fetch_assoc()) { 
     $arr[] = $row; 
    } 
} 
echo '<pre>'; 
print_r($arr); 
echo '</pre>'; 

$phrase = "You should eat fruits, vegetables, and fiber every day."; 
//$healthy = array("fruits", "vegetables", "fiber"); 
//$yummy = array("pizza", "beer", "ice cream"); 
$newphrase = str_replace($arr['txtSearch'], $arr['txtReplace'], $phrase); 
echo $phrase . "<br />" . $newphrase; 

回答

1

有錯在你的搜索和替換數組。他們需要是字符串數組。

$arr = array('txtSearch' => array(), 'txtReplace' => array()); 
if($result->num_rows > 0) { 
    while($row = $result->fetch_assoc()) { 
     $arr['txtSearch'][] = $row['txtSearch']; 
     $arr['txtReplace'][] = $row['txtReplace']; 
    } 
} 

然後:

$newphrase = str_replace($arr['txtSearch'], $arr['txtReplace'], $phrase); 
+0

作品完美捆綁感謝 – Rtra

1

鑑於當前的代碼,你需要提取txtSearchtxtReplace成一個單一的維度:

$s = array_column($arr, 'txtSearch'); 
$r = array_column($arr, 'txtReplace'); 
$newphrase = str_replace($s, $r, $phrase); 

或者使用一個數組:

$x = array_column($arr, 'txtReplace', 'txtSearch'); 
$newphrase = str_replace(array_keys($x), $x, $phrase); 

或甚至更好使用strtr()

$newphrase = strtr($phrase, array_column($arr, 'txtReplace', 'txtSearch'));