Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
544 views
in Technique[技术] by (71.8m points)

php - Get uncommon values from two or more arrays

Is there any function in PHP which will give an array of uncommon values from two or more arrays?

For example:

$array1 = array( "green", "red", "blue");
$array2 = array( "green", "yellow", "red");
....
$result = Function_Needed($array1, $array2,...);
print_r($result);

Should give the output:

array("blue", "yellow", ...);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use array_diff and array_merge:

$result = array_merge(array_diff($array1, $array2), array_diff($array2, $array1));

Here's a demo.

For multiple arrays, combine it with a callback and array_reduce:

function unique(&$a, $b) {
    return $a ? array_merge(array_diff($a, $b), array_diff($b, $a)) : $b;
}

$arrays = array(
    array('green', 'red', 'blue'),
    array('green', 'yellow', 'red')
);

$result = array_reduce($arrays, 'unique');

And here's a demo of that.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...