如果存在子数组中的值,则显示父键

时间:2014-05-13 19:18:24

标签: php arrays multidimensional-array

我创建了一个包含两个变量$ state和$ sector的脚本。如果州在该部门,我想显示该部门。下面的示例使用'Arizona'作为状态,它应该将扇区输出为'southwest'但我不认为我正在使用数组:

    <?php

    $state = 'Arizona';

    $sectors = array(
                "Southeast" => array(
                        'name' => 'Southeast',
                        'states'    => array('Alabama', 'Georgia', 'Florida', 'South Carolina', 'North Carolina', 'Louisiana', 'Tennessee', 'Kentucky', 'West Virginia', 'Mississippi')
                ),
                    "Southwest" => array(
                            'name' => 'Southwest',
                            'states'    => array('California', 'Arizona', 'New Mexico', 'Utah')
                    )
    );

        function has_recursive($sectors, $state)
        {
            foreach ($state as $key => $value) {
                if (!isset($sectors[$key])) {
                    return false;
            }
            if (is_array($sectors[$key]) && false === has_recursive($sectors[$key], $value)) {
                return false;
            }
        }
        return true;
    }

    if (has_recursive($sectors, $state) == true){
     // false or true
        echo $sector['name'];  // Displays Southwest
    }

请帮忙。

2 个答案:

答案 0 :(得分:0)

试试这个:

function get_sector($sector_array, $state_name) {

    foreach ($sector_array as $sec) 
        if (in_array($state_name, $sec))
            return $sec['name'];

    return false;
}

根据您的问题定义$state$sectors ......

echo get_sector($sectors, $state); // prints "Southwest"

关于评论的更新:

“找不到”返回值有几种不同的方法。什么最适合您的应用程序取决于您,但这里有几个例子:

return false;

//This would be used like this:
if (!$sect = get_sector($sectors, $state))
    echo "A custom error message"
else
    echo "Sector = " . $sect;

或者你可以返回一个特定的字符串:

return "Sector not found."; 
// Return a standard error message

或自定义字符串:

return "No sector match for the state of " . $state_name; 
// Return a specific error message

答案 1 :(得分:0)

此功能应该有效。

function getSector($stateName, $sectorList) {
   foreach($sectorList as $sector) {
      if( in_array($stateName, $sector['states'] ) {
         return $sector['name'];   
      }
   }
 // If state is not found
 return 'NOT FOUND';
}

代码中使用的示例是:

echo getSector($state, $sectors);