Want to got the new array that not in array A?

2019-07-26 03:52发布

I have two arrays:

$A = array('a','b','c','d')
$c = array('b','c','e','f')

I want to get a new array containing items not in array $A. So it would be:

$result = array('e','f');

because 'e' and 'f' are not in $A.

标签: php
4条回答
Ridiculous、
2楼-- · 2019-07-26 04:29

Use array_diff
print_r(array_diff($c, $A)); returns

Array
(
    [2] => e
    [3] => f
)
查看更多
地球回转人心会变
3楼-- · 2019-07-26 04:30

Use array_diff for this task. As somewhat annoying it does not return all the differences between the two arrays. Only the elements from the first array passed which are not found in any other array passed as argument.

$array1 = array('a','b','c','d');
$array2 = array('b','c','e','f');
$result = array_diff($array2, $array1);
查看更多
Luminary・发光体
5楼-- · 2019-07-26 04:56

Pseduo Code for General Implementation

Disclaimer: Not familiar with PHP, other answers indicate there are a lot quicker ways of doing this :)

Loop through your first array:

// Array of results
array results[];

// Loop through all chars in first array
for i = 0; i < A.size; i++
{
    // Have we found it in second array yet?
    bool matched = false;

    // Loop each character in 2nd array
    for j = 0; j < C.size; j++
    {
        // If they match, exit the loop
        if A[i] == C[J] then
            matched = true;
            exit for;
    }

    // If we have a match add it to results
    if matches == true then results.add(A[i])

}
查看更多
登录 后发表回答