我有 2 个字符串,我想比较差异并使用这些不同项目的值。例如:
$stringA = "1, 2, 3, 4, 5"
$stringB = "1, 2, 4, 5, 6"
所以与 stringB 的区别在于缺少 '3' 并添加了 '6'。
我想执行一个使用值“3”和“6”的函数。为了将其放在上下文中,想象一下在 MySQL 查询中使用字符串,其中我只想更新 id 3 和 6 的记录,因为它们已更改,因此需要更新,但其余部分保持不变,因此无需更新数据库记录那些。我希望这是有道理的?
如何使用 PHP 获取差异并确保结果再次是带有逗号分隔值的字符串?即
$stringDifference = "3, 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 作为新的脚本编辑器。
关于php - 比较逗号分隔字符串之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15696821/