在php中搜索数组?

时间:2012-01-12 00:12:43

标签: php arrays

我在页面下方有数组。我想找到[itag] =>的数组编号22。 在这个例子中,这是[1],意思是:

[1] => Array
        (
            [url] => asd2
            [quality] => hd720
            [fallback_host] => ax2
            [type] => video/mp4; codecs=\"avc1.64001F, mp4a.40.2\"
            [itag] => 22
        )

我怎么能在这些数组结构中找到它:?

    Array
(
    [0] => Array
        (
            [url] => asd1
            [quality] => hd720
            [fallback_host] => ax1
            [type] => video/webm; codecs=\"vp8.0, vorbis\"
            [itag] => 45
        )

    [1] => Array
        (
            [url] => asd2
            [quality] => hd720
            [fallback_host] => ax2
            [type] => video/mp4; codecs=\"avc1.64001F, mp4a.40.2\"
            [itag] => 22
        )

    [2] => Array
        (
            [url] => asd3
            [quality] => large
            [fallback_host] => ax3
            [type] => video/webm; codecs=\"vp8.0, vorbis\"
            [itag] => 44
        )

    [3] => Array
        (
            [url] => asd4
            [quality] => large
            [fallback_host] => ax4
            [type] => video/x-flv
            [itag] => 35
        )



)

2 个答案:

答案 0 :(得分:1)

这是一种低技术解决方案,没有任何花哨的东西:

$matchKey = null;
foreach($array as $key => $item) {
    if ($item['itag'] == 22) {
         $matchKey = $key;
         break;
    }
}

if($matchKey === null) {
    echo 'Not found.';
}
else {
    echo 'Key found: '.$matchKey;
}

答案 1 :(得分:0)

array_filter:http://php.net/manual/en/function.array-filter.php

<?php
$matches = array_filter($arr, function($el) {
  return $el['itag'] == 22;
});
print_r($matches);
// or
$key = key($matches);
?>

如果22是变量,则必须将其导入/使用到闭包的范围内:

...
$matches = array_filter($arr, function($el) use ($someVar) {
  return $el['itag'] == $someVar;
...