BerkErarslan
BerkErarslan

Reputation: 69

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

Upvotes: 0

Views: 152

Answers (2)

Jon
Jon

Reputation: 437794

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

Upvotes: 1

Rudie
Rudie

Reputation: 53881

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

If 22 is a variable, you'll have to import/use it into the closure's scope:

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

Upvotes: 0

Related Questions