PHP按键搜索多维关联数组并返回key => value

Bob*_*ing 0 php arrays

嗨,我有一个多维关联数组:

   $array= array(
            'Book1' => array('http://www.google.com', '45' ),
            'Book2' => array('http://www.yahoo.com', '46', )
)
Run Code Online (Sandbox Code Playgroud)

我需要能够在'BookX'上搜索$ array,然后返回'BookX'的内容.

我试过了:

  function array_searcher($needles, $array) 
    { 
   foreach ($needles as $needle) {

    foreach ($array as $key ) 
        { 

            if ($key == $needle) 
                { 
                echo $key; 
                } 

        }
        }
  } 
Run Code Online (Sandbox Code Playgroud)

随着搜索

$needles  = array('Book1' , 'Book2' ); 
Run Code Online (Sandbox Code Playgroud)

但这并不能归还任何东西

Pau*_*lRe 6

我可能会误解,但这听起来像是访问者.如果没有,你能澄清一下吗?

$array= array(
    'Book1' => array('http://www.google.com', '45' ),
    'Book2' => array('http://www.yahoo.com', '46', )
);

echo $array['Book1'];
Run Code Online (Sandbox Code Playgroud)

编辑:我确实误解了你的目标.我对做两个foreach循环做了评论.虽然这确实有效,但当你有一个非常大的干草堆阵列时,性能会受到影响.我建议isset()用于测试大海捞针阵列中是否存在针.

我修改了函数以返回找到结​​果的数组,以从输出到stdout中删除任何性能命中.我运行了以下性能测试,虽然它可能不会反复进行相同的搜索,但它指出了当您的数组很大时执行两个foreach循环的效率低下:

function array_searcher($needles, $array) {

    $result = array();

    foreach ($needles as $needle) {
        foreach ($array as $key => $value) {
            if ($key == $needle) {
                $result[$key] = $value;
            }
        }
    }

    return $result;
}

function array_searcher2($needles, $array) {

    $result = array();

    foreach ($needles as $needle) {
        if (isset($array[$needle])) {
            $result[$needle] = $array[$needle];
        }
    }

    return $result;
}

// generate large haystack array
$array = array();
for($i = 1; $i < 10000; $i++){
    $array['Book'.$i] = array('http://www.google.com', $i+20);
}

$needles = array('Book1', 'Book2');

$start = microtime(true);
for ($i = 0; $i < 1000; $i++) {
    array_searcher($needles, $array);
}
echo (microtime(true) - $start)."\n";
// 14.2093660831

$start = microtime(true);
for ($i = 0; $i < 1000; $i++) {
    array_searcher2($needles, $array);
}
echo (microtime(true) - $start)."\n";
// 0.00858187675476
Run Code Online (Sandbox Code Playgroud)