Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching a recursive/multidimensional array against another array

Tags:

php

I have the following array (called $example_array below):

array(3) {
  ["id"]=> string(4) "123"
  ["name"]=>
      array(1) {
        ["first"]=> string(3) "pete"
        ["last"]=> string(3) "foo"
      }
  ["address"]=>
      array(1) {
        ["shipping"]=>
            array(1) {
              ["zip"]=> string(4) "1234"
              ["country"]=> string(4) "USA"
            }
      }
}

I would like a function that I can run against arrays like this and look for a match. Here are the searches that I would like to be able to perform:

// These should return true:
search( $example_array, array( 'id' => '123' ) );
search( $example_array, array( 'name' => array( 'first' => 'pete' ) );
search( $example_array, array( 'address' => array( 'shipping' => array( 'country' => 'USA' ) ) );

// These don't have to return true:
search( $example_array, array( 'first' => 'pete' ) );
search( $example_array, array( 'country' => 'USA' ) );

Is there a PHP internal function that I can use or will I have to code something myself?

like image 784
Louis B. Avatar asked Dec 27 '12 11:12

Louis B.


2 Answers

function search($array, $b) {
    $ok = true;
    foreach ($b as $key => $value) {
        if (!isset($array[$key])) { $ok = false; break; }
        if (!is_array($value))
            $ok = ($array[$key] == $value);
        else 
            $ok = search($array[$key], $value);
        if ($ok === false) break;
    }
    return $ok;
}

Here's the test script.

like image 195
Shoe Avatar answered Oct 31 '22 11:10

Shoe


Hope this function helps:

public function matchArray(&$arrayToSearch, $valueToMatch = array()){
    if(!is_array($valueToMatch))
        $valueToMatch = array($valueToMatch);

    $exists = false;
    $indexToMatch = array_keys($valueToMatch);

    foreach($indexToMatch as $ind){
        if(array_key_exists($ind, $arrayToSearch)){
            $valToMatch = $valueToMatch[$ind];
            $value = $arrayToSearch[$ind];
            $valType = gettype($value);
            $valToMatch = $valueToMatch[$ind];
            if($valType == gettype($valToMatch) || is_numeric($valToMatch)){
                if($valType == 'array'){
                    $exists = $this->matchArray($value, $valToMatch);
                } else if(($valType == 'string' || is_numeric($valToMatch)) && $valToMatch == $value) {
                    $exists = true;
                } else {
                    $exists = false;
                    break;
                }
            }
        }
    }

    return $exists;
}
like image 33
gezimi005 Avatar answered Oct 31 '22 11:10

gezimi005