3

我有 2 个字符串,我想比较差异并使用不同项目的值。例如:

$stringA = "1, 2, 3, 4, 5"
$stringB = "1, 2, 4, 5, 6"

所以与 stringB 的区别在于缺少 '3' 而添加了 '6'。

我想执行一个使用值“3”和“6”的函数。为了把它放在上下文中,假设字符串用于 MySQL 查询,我只想更新 id 为 3 和 6 的记录,因为它们已更改,因此需要更新,但其余部分保持不变,因此无需更新数据库记录那些。我希望这是有道理的?

我如何使用 PHP 获得差异并确保结果再次是带有逗号分隔值的字符串?IE

$stringDifference = "3, 6"
4

2 回答 2

6

刚刚在我的机器上运行了代码,这将解决问题

$stringA = "1, 2, 3, 4, 5";
$stringB = "1, 2, 4, 5, 6";

$stringA = explode(',', $stringA);
$stringB = explode(',', $stringB);

$Difference_1 = array_diff($stringA, $stringB); // Check string A Against String B
$Difference_2 = array_diff($stringB, $stringA); // Check String B against String A
$Difference = array_merge($Difference_1, $Difference_2); // Merge the two difference arrays together 
$Difference = implode(',', $Difference); // Convert to a string
echo "The Difference Between The Two Is: ".$Difference; // Echo the difference

更新

function Differences ($Arg1, $Arg2){
    $Arg1 = explode (',', $Arg1);
    $Arg2 = explode (',', $Arg2);

    $Difference_1 = array_diff($Arg1, $Arg2);
    $Difference_2 = array_diff($Arg2, $Arg1);
    $Diff = array_merge($Difference_1, $Difference_2);
    $Difference = implode(',', $Diff);
    return "The Difference Between The Two Is: ".$Difference;
}

$stringA = "1, 2, 3, 4, 5";
$stringB = "1, 2, 4, 5, 6";


// Call By:

echo Differences($stringA, $stringB);

很抱歉延迟更新。我已经习惯了 PHPStorm 作为一个新的脚本编辑器。

于 2013-03-29T03:27:58.757 回答
0
function getDif(stringA, stringb){
    $stra = explode(",", $stringA);
    $strb = explode(",", $stringB);
    $viola = array_diff($stra,$strb);
    return  $voila
}
于 2013-03-29T03:36:44.550 回答