搜索特定字符串的数组 [英] Search array for specific string

查看:56
本文介绍了搜索特定字符串的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从数组中输出一个特定的值,但是每次运行该数组时该值都在不同的位置,如下所示:

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:

在一页上:

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

在另一个页面上:

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

如您所见,一个页面上的 'GB' 字符串位于数组中的位置 0,而在另一个页面中,它位于位置 1.现在,此代码正在部署到的页面是动态的,因此我不能只是硬编码 $array['countries'][0]['release_date'],其中 'release_date' 是我想从数组中提取的实际值,所以我'我想我需要代码来在数组中搜索GB"(或美国",或任何需要返回的国家/地区),找到包含字符串的索引号,然后将其作为 $uk_release_date 动态放入查询中,或者一些这样的命名变量.

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.

提前致谢!

推荐答案

$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

这篇关于搜索特定字符串的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆