基于字符串前缀优化子数组的创建

时间:2011-12-07 18:10:38

标签: php arrays string

在我的上一篇question中,创建了一种基于字符串模式 Father_son 划分数组的方法,但现在我需要一种方法来分割新的模式: Father_N_son

原创(由http://ideone.com/pmHHR代码生成):

array
  'Pagamento' => 
    array
      'data' => string '' (length=0)
      '0_pessoaId' => string '85' (length=2)
      '0_valorBruto' => string '890.00' (length=6)
      '1_pessoaId' => string '83' (length=2)
      '1_valorBruto' => string '20.00' (length=5)

现在我需要:

array
  'Pagamento' => 
    array
      'data' => string '' (length=0)
      0 => 
        array
          'pessoaId' => string '85' (length=2)
          'valorBruto' => string '890.00' (length=6)
      1 => 
        array
          'pessoaId' => string '83' (length=2)
          'valorBruto' => string '20.00' (length=5)

谢谢, 塞尔索

1 个答案:

答案 0 :(得分:0)

我的正则表达式解决方案:

static function parserRequest($array = null) {

        if (empty($array)) {
            $array = $_REQUEST;
        }

        foreach ($array as $k => $v) {

            $name = explode('_', $k);
            $newkey = array_shift($name);
            $newname = implode('_', $name);

            //para o padrão Entidade.n.atributo
            if(preg_match("/[0-9]_[a-z]/", strtolower($newname))){

                $nameValued    = explode('_',$newname);
                $newkeyValued  = array_shift($name);
                $newnameValue  = implode('_', $name);

                $result[$newkey][$newkeyValued][$newnameValue] = $v;

            }else{

                //para o padrão Entidade.atributo
                $result[$newkey][$newname] = $v;

            }

        }

        return $result;
    }