简体   繁体   中英

How to check if values of one array exists as values or keys of another array?

$word = array("red","or","bl","green","gr");

$colors = array( "re"=>"red" ,
                     "or"=>"orange",
                     "bc"=>"black" ,
                     "br" =>"brown",
                     "gr" =>"green"

        );

//find the values of array word in array colors doesn't matter if its key or value.
//output should display both key and value.

re => red

or => orange

gr => green

Here is a function to compute the intersection(?) of both the key and values to $array from an array $contains:

function array_full_intersect($array, $contains) {
    $result = array();
    // Go through each element in $contains.
    foreach ($contains as $val) {
        // If $val is a key in $array, add key-value pair to $result.
        if (isset($array[$val])) {
            $result[$val] = $array[$val];
        } else {
            // Otherwise, if $val is a value in $array, search for the value and get its key.
            // Add key-value pair to $result.
            $key = array_search($val, $array);
            if ($key !== false) {
                $result[$key] = $val;
            }
        }
    }

    return $result;
}

If you would prefer a more compact solution, use what is described in the comments:

function array_full_intersect($array, $contains) {
    return array_merge(array_intersect_key($array, array_flip($contains)), array_intersect($array, $contains));
}

Use as:

$result = array_full_intersect($colors, $word);

Using PHP array functions:

$values = array_intersect($colors, $word);
$flip = array_flip($colors);
$flipValues = array_intersect($flip, $word);
$keys = array_flip($flipValues);
$result = array_merge($values, $keys);

Taking this apart:

  1. $values = array_intersect($colors, $word);

creates an array with all of the members of $colors whose value is the same as a value in $word, ie

    $values = array(
                 "re"=>"red",
                 "gr" =>"green"
     );

2. $flip = array_flip($colors);

This flips the keys and values of $colors, so it is:

$flip = array( "red" => "re",
               "orange" => "or",
               "black" => "bc",
               "brown" => "br",
               "green" => "gr"

    );
  1. $flipValues = array_intersect($flip, $word);

This uses array_intersect again, but on the keys (which are the values in $flip). So this will be

$flip = array( "orange" => "or",
               "green" => "gr"
    );

4. $keys = array_flip($flipValues);

This flips the results back again:

$keys= array( "or" => "orange",
              "gr" => "green"
    );

Then array_merge combines $values and $keys eliminating duplicates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM