Bob*_*300 2 php string compare
我有2个字符串,我想比较差异并使用不同的项目的值.例如:
$stringA = "1, 2, 3, 4, 5"
$stringB = "1, 2, 4, 5, 6"
Run Code Online (Sandbox Code Playgroud)
因此与stringB的区别在于缺少'3'并且添加了'6'.
我想执行一个使用值'3'和'6'的函数.要把它放在上下文中,想象一下在MySQL查询中使用字符串,我想只更新id为3和6的记录,因为它们已经改变,所以需要更新,但其余的保持不变,所以不需要更新数据库记录那些.我希望这是有道理的?
我如何使用PHP获得差异并确保结果再次是一个逗号分隔值的字符串?即
$stringDifference = "3, 6"
Run Code Online (Sandbox Code Playgroud)
刚刚浏览了我的机器上的代码,这将解决问题
$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
Run Code Online (Sandbox Code Playgroud)
更新
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);
Run Code Online (Sandbox Code Playgroud)
对不起延迟更新.我已经习惯了PHPStorm作为一个新的脚本编辑器.