使用Json将数据转换为数组

时间:2018-06-05 16:43:20

标签: php arrays json

你好,我有这个带递归的脚本,我试着用$_POST中的变量来评估提取具有Json格式的那些变量:

发布数据:

array(1) {
  ["jsonData"]=>
  string(159) "[{"s_file_1":"Prueba 3"},{"text_file_1":"ORT0000133.pdf"},{"s_file_2":"Prueba 5"},{"text_file_2":"factura.pdf"},{"idform":"f-gen-desk"},{"idprocess":"p-save"}]"
}

评估数据的脚本:

public function BuildV($_VARS) {
        if (is_array($_VARS)) {
            foreach ($_VARS as $val) {
                $chk = $this->BuildV($val);
                if ($chk) {
                    return json_decode($val, true);
                } else {
                    return $val;
                }
            }
        } else {
            return $chk = (json_decode($_VARS) != NULL) ? true : false;
        }
   }

$_VARS = $_POST;
$_VARS = $this->BuildV($_VARS);

结果:

array(6) {
  [0]=>
  array(1) {
    ["s_file_1"]=>
    string(8) "Prueba 3"
  }
  [1]=>
  array(1) {
    ["text_file_1"]=>
    string(14) "ORT0000133.pdf"
  }
  [2]=>
  array(1) {
    ["s_file_2"]=>
    string(8) "Prueba 5"
  }
  [3]=>
  array(1) {
    ["text_file_2"]=>
    string(11) "factura.pdf"
  }
  [4]=>
  array(1) {
    ["idform"]=>
    string(10) "f-gen-desk"
  }
  [5]=>
  array(1) {
    ["idprocess"]=>
    string(6) "p-save"
  }
}

但我需要这种格式:

array(4) {
  ["s_file_1"]=>
  string(8) "Prueba 3"
  ["text_file_1"]=>
  string(14) "ORT0000133.pdf"
  ["s_file_2"]=>
  string(8) "Prueba 5"
  ["text_file_2"]=>
  string(11) "factura.pdf"
}

如何简化或消除以数字方式开始的数组索引。

All the Input will have a structure:
name='i_text_####'; # for input type text
name='i_num_####'; # for input type num
name='s_text_####'; # for input type select option
name='t_text_####'; # for input type textarea
name='ch_text_####'; # for input type checkbox

名称标签中的符号#表示可以重复的次数。

1 个答案:

答案 0 :(得分:0)

我已将此添加到要解决的脚本中:

$_VARS = $_POST;
$_VARS = $this->BuildV($_VARS);
$_VARS = array_reduce($_VARS, 'array_merge', array());

获取此输出:

array(6) {
  ["s_file_1"]=>
  string(8) "Prueba 3"
  ["text_file_1"]=>
  string(14) "ORT0000133.pdf"
  ["s_file_2"]=>
  string(8) "Prueba 5"
  ["text_file_2"]=>
  string(11) "factura.pdf"
  ["idform"]=>
  string(10) "f-gen-desk"
  ["idprocess"]=>
  string(6) "p-save"
}