phparraysmultidimensional-arrayfilter

Search a 2d array for a row containing a qualifying column value and return its parent key


I have array like below the page. I want to find array number which [itag] => 22 . In this example this is [1], means:

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

How could I find this in these array structure?

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
        )
)

Solution

  • And a low-tech solution, without anything fancy:

    $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;
    }