douzhang3822
2013-06-13 16:26
浏览 33
已采纳

PHP:从嵌套关联数组中查找动态元素

I'm working on a function that looks like this:

public function myfunction($mainArr, $keys) {
    // $mainArr: a nested associative array
    // $keys: a simple array of strings, example: array('string_1', 'string_2', 'string_3')
    $totalKeys = count(keys);
    if(totalKeys == 1) {
        return mainArr[keys[0]];
    } else if(totalKeys == 2) {
        return mainArr[keys[0]][keys[1]];
    } else if(totalKeys == 3) {
        return mainArr[keys[0]][keys[1]][keys[2]];
    } else if(totalKeys == 4) {
        return mainArr[keys[0]][keys[1]][keys[2]][keys[3]];
    } else if(totalKeys == 5) {
        return mainArr[keys[0]][keys[1]][keys[2]][keys[3]][keys[4]];
    }
    // the same pattern continues..
}

I want to change this function into something more dynamic rather than a big list of "if" conditions, is it possible somehow?

图片转代码服务由CSDN问答提供 功能建议

我正在研究一个如下所示的函数:

 <  code> public function myfunction($ mainArr,$ keys){
 // $ mainArr:一个嵌套的关联数组
 // $ keys:一个简单的字符串数组,例如:array('string_1','string_2','  string_3')
 $ totalKeys = count(keys); 
 if(totalKeys == 1){
 return mainArr [keys [0]]; 
} else if(totalKeys == 2){
 return mainArr  [keys [0]] [keys [1]]; 
} else if(totalKeys == 3){
 return mainArr [keys [0]] [keys [1]] [keys [2]]; 
  } else if(totalKeys == 4){
 return mainArr [keys [0]] [keys [1]] [keys [2]] [keys [3]]; 
} else if(totalKeys == 5)  {
返回mainArr [keys [0]] [keys [1]] [keys [2]] [keys [3]] [keys [4]]; 
} 
 //相同的模式继续.. \  n} 
   
 
 

我想将此函数更改为更动态的内容,而不是“if”条件的大列表,是否可能以某种方式? \ n

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dousuo2812 2013-06-13 16:37
    已采纳

    You can do it for example this way:

    function get_value(array $source, array $keys) {
        foreach ($keys as $key) {
            if (isset($source[$key])) {
                $source = $source[$key];
            }
            else {
                return null;
            }
        }
    
        return $source;
    }
    

    If $keys describes an invalid path inside $source then null will be returned.

    点赞 打赏 评论

相关推荐 更多相似问题