Alex Ryans
Alex Ryans

Reputation: 1935

Search array for specific string

I am trying to output a specific value from an array, however the value is in a different place each time the array is run, as below:

On one page:

Array
(
    [id] => 12445
    [countries] => Array
        (
            [0] => Array
                (
                    [iso_3166_1] => GB
                    [certification] => 12A
                    [release_date] => 2011-07-07
                )

            [1] => Array
                (
                    [iso_3166_1] => US
                    [certification] => PG-13
                    [release_date] => 2011-07-15
                )

            [2] => Array
                (
                    [iso_3166_1] => DE
                    [certification] => 12
                    [release_date] => 2011-07-12
                )
}

On another page:

Array
(
    [id] => 673
    [countries] => Array
        (
            [0] => Array
                (
                    [iso_3166_1] => US
                    [certification] => PG
                    [release_date] => 2004-06-04
                )

            [1] => Array
                (
                    [iso_3166_1] => GB
                    [certification] => PG
                    [release_date] => 2004-05-31
                )

            [2] => Array
                (
                    [iso_3166_1] => IT
                    [certification] => T
                    [release_date] => 2004-06-04
                )
}

As you can see, the 'GB' string on one page is at position 0 in the array and, in the other, it is at position 1. Now, the page which this code is being deployed onto is dynamic, so I can't just hard-code $array['countries'][0]['release_date'], where 'release_date' is the actual value I want to pull from the array, so I'm thinking I'd need the code to search through the array for 'GB' (or 'US', or whatever country needs returning), find the index number containing the string and dynamically put that into the query as $uk_release_date, or some such named variable.

Thanks in advance!

Upvotes: 0

Views: 124

Answers (1)

Husman
Husman

Reputation: 6909

$index = -1;

foreach($array['countries'] as $k=>$v) {
  if(array_search('GB', $v)) { // Search for GB
    $index = $k;
    break;
  }
}

echo $array['countries'][$index]['release_date']; // This will be the release date for GB

Upvotes: 1

Related Questions