PHP/MySQL数组替换函数不工作

PHP/MySQL数组替换函数不工作,php,mysql,arrays,Php,Mysql,Arrays,我试图用数组替换SQL表中所有可用的文本,但我不知道如何完成。我成功地获得了所有结果,但无法在str_replace()函数中使用它 这是我的数组 Array ( [0] => Array ( [txtSearch] => fruits [txtReplace] => pizza ) [1] => Array ( [txtSearch]

我试图用数组替换SQL表中所有可用的文本,但我不知道如何完成。我成功地获得了所有结果,但无法在str_replace()函数中使用它

这是我的数组

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;
include('site-primary-config.php');
$select=“从tblreplacements中选择txtSearch、txtplace”;
$result=$conn->query($select)或die($conn->error.\uu_uu行\uuu);
$arr=array();
如果($result->num_rows>0){
而($row=$result->fetch_assoc()){
$arr[]=$row;
}
}
回声';
印刷费($arr);
回声';
$PHASE=“你应该每天吃水果、蔬菜和纤维。”;
//$Health=数组(“水果”、“蔬菜”、“纤维”);
//$yummy=数组(“比萨饼”、“啤酒”、“冰淇淋”);
$newphrase=str_replace($arr['txtSearch'],$arr['txtsreplace'],$phrase);
回音$短语。“
”$新短语;
搜索和替换数组时出错。它们需要是字符串数组

$newphrase = str_replace($arr['txtSearch'], $arr['txtReplace'], $phrase);
然后:

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

给定当前代码,您需要将
txtSearch
txtsreplace
提取到单个维度中:

$x = array_column($arr, 'txtReplace', 'txtSearch');
$newphrase = str_replace(array_keys($x), $x, $phrase);
或者使用一个数组:

$newphrase = strtr($phrase, array_column($arr, 'txtReplace', 'txtSearch'));
或者更好地使用strtr():

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