从PHP多维数组搜索返回键

时间:2017-01-06 17:02:41

标签: php

我有一个包含Regions和States的数组。每个区域都有多个国家。我想在数组中搜索一个State并让它告诉我它所在的Region。我正在搜索的状态最终会通过表单发送到这个函数。

我已经尝试了一些我在这里找到的东西,例如in_array和自定义函数,但似乎无法让它工作。我使用的是PHP 5.3.27,无法升级到5.5+,因此我必须依赖早期版本的可用功能。

这是我的阵列:

$regions = array("SE" => array("NC","SC","GA","KY","AL","LA","MS","FL","TN"), "MW" => array("IN","IL","OH","WI","MI"), "SW" => array("MO","OK","KS","AR","TX"), "W" => array("CA","NV"));

1 个答案:

答案 0 :(得分:0)

这应该有效

<?php
$state = $_POST["whatever"];

$regions = array("SE" => array("NC","SC","GA","KY","AL","LA","MS","FL","TN"), "MW" => array("IN","IL","OH","WI","MI"), "SW" => array("MO","OK","KS","AR","TX"), "W" => array("CA","NV"));
foreach ($regions as $key => $region){
    if (in_array($state, $regions[$key])){
        echo $key;
        break;
    }
} 
?>