代码之家  ›  专栏  ›  技术社区  ›  Ken J

PHP-简化处理数组的方法

  •  1
  • Ken J  · 技术社区  · 11 年前

    在处理数组时,我被迫添加一堆重复代码来处理一个子数组而不是多个子数组:

    //If more than one step, process each step, elcse processs single
            if(!array_key_exists('command',$pullcase['steps']['step'])) {
                foreach($pullcase['steps']['step'] as $step) {
                    $command=$step['command'];
                    $parameter=$step['parameter'];
                    if(isset($step['value'])){ 
                        $value = $step['value']; 
                        $this->runCommands($command,$parameter,$value); 
                    } else { 
                        $this->runCommands($command,$parameter); 
                    }
                }
            } else {
                $command = $pullcase['steps']['step']['command'];
                $parameter = $pullcase['steps']['step']['parameter'];
                if(isset($pullcase['steps']['step']['value'])){ 
                    $value = $pullcase['steps']['step']['value']; 
                    $this->runCommands($command,$parameter,$value); 
                }
                else { $this->runCommands($command,$parameter); }
            }
    

    如您所见,我必须重复我的工作,这取决于阵列中是否有单个项而不是多个项:

    $pullcase['steps']['step'][0]['command'] 
    

    $pullcase['steps']['step']['command']
    

    如何简化此代码,以便对所有实例使用单个变量?

    2 回复  |  直到 11 年前
        1
  •  1
  •   AbraCadaver    11 年前

    如果控制阵列的创建,请 step 一个数组,即使只有一个,所以总是有一个数组。这可能吗?

    你要么有一个 大堆 [step][0][command] 或者你只有一步 [step][command] 。因此,当您创建数组而不是 [步骤][命令] 成功 [步骤][0][命令] 标准的做法,解决问题,因为您只需要 foreach .

    如果无法在创建数组时执行此操作,请考虑在循环之前执行此操作:

    if(is_array($pullcase['steps']['step'])) {
        $steps = $pullcase['steps']['step'];
    } else {
        $steps[] = $pullcase['steps']['step'];
    }
    foreach($steps as $step) {
        $value = isset($step['value']) ? $step['value'] : null;
        $this->runCommands($step['command'], $step['parameter'], $value); 
    }
    

    此外,如果 runCommands() 可以检测空参数,然后可以检测 if/else 对于上面使用的函数调用。

        2
  •  0
  •   kainaw    11 年前

    以下内容可能会有所帮助。如果键是'command',它只会对值调用函数“runcommands”。我用它来展示如何使用array_walk_rescrave来解决问题。

    首先,您需要使用函数:

    function runcommandswhencommand($value, $key)
    {
      if($key == 'command') runcommands($value);
    }
    

    现在,您可以在阵列上使用递归遍历:

    array_walk_recursive($pullcase, 'runcommandswhencommand');
    

    这样,每当键为“command”时,该索引的值将在函数runcommands()的参数中使用。

    推荐文章