0

我有一个带有示例的小脚本:

两个字符串,我想在其中获得不同的数字

$first = "|x|67|x|194|x|113|x|6|x|";
$second = "|x|194|x|113|x|6|x|109|x|";

分解它们,得到纯​​数字

$first_array = explode("|x|", $first);
$second_array = explode("|x|", $second);

获得差异

$result_array = array_merge(array_diff($first_array, $second_array), array_diff($second_array, $first_array));

查看结果

$result = implode(",", $result_array);

我的问题是:

如何从第一个字符串中添加哪个数字以及哪个数字被删除?

4

3 回答 3

0
<?PHP
$first = "|x|67|x|194|x|113|x|6|x|";
$second = "|x|194|x|113|x|6|x|109|x|";

$first_array = explode("|x|", $first);
$second_array = explode("|x|", $second);

$not_in_first_array = array();
$not_in_second_array = array();

foreach( $first_array as $a )
{
    if( ! in_array( $a , $second_array ) )
    {
        $not_in_second_array[] = $a;
    }
}

foreach( $second_array as $a )
{
    if( ! in_array( $a , $first_array ) )
    {
        $not_in_first_array[] = $a;
    }
}

print_r( $not_in_second_array );
print_r( $not_in_first_array );
?>
于 2013-09-02T08:49:03.640 回答
0

您可以尝试以下方法:

<?PHP
$first = "|x|67|x|194|x|113|x|6|x|";
$second = "|x|194|x|113|x|6|x|109|x|";

$first_array = explode("|x|", $first);
$second_array = explode("|x|", $second);

// Get all the values
$allValues = array_filter(array_merge($first_array, $second_array));

// All values which ware the same in the first en second array, and will be removed
$removedValues= array_intersect($first_array, $second_array);

// All new values from the second array
$newValues = array_diff($second_array, $first_array);
于 2013-09-02T08:56:10.743 回答
0
//Removed from first string
$removed_from_first_string = array_diff($first_array, $result_array);
print_r($removed_from_first_string);

//Added from second string
$added_from_second_string = array_diff($second_array, $removed_from_first_string);
print_r($added_from_second_string);
于 2013-09-02T09:19:15.010 回答