将递归/多维数组与另一个数组匹配

Lou*_* B. 7 php

我有以下数组($example_array如下所示):

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"
            }
      }
}
Run Code Online (Sandbox Code Playgroud)

我想要一个函数,我可以对这样的数组运行,并寻找匹配.以下是我希望能够执行的搜索:

// 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' ) );
Run Code Online (Sandbox Code Playgroud)

是否有我可以使用的PHP内部函数,或者我必须自己编写代码?

Sho*_*hoe 7

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;
}
Run Code Online (Sandbox Code Playgroud)

这是测试脚本.