PHP / MySQL数组替换功能不起作用

时间:2017-09-11 17:57:15

标签: php mysql arrays

我正在尝试使用数组替换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;

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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'));