0

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!

1

1 Answer 1

1
$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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this was the first solution I tried, and it worked perfectly!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.