多维数组:获取第二个键并使用它创建第一个键

时间:2013-11-21 11:36:40

标签: php arrays file-upload multidimensional-array

更新: 感谢Bhavik Shah,我设法像这样循环了它。

$file_data = array();
            foreach($files as $key => $value ){
                foreach($value as $name => $name_data ) {
                    $file_data[$name] = $files;
                }
            }
            $result = array_merge($data, $file_data);

原始问题:

我上传的HTML表单包含文本输入和文件。然后我必须合并$ _POST和$ _FILES数组来循环它们通过一些函数(健全性检查)。合并时得到的是:

Array
(
    [name] => A name
    [description] => A description
    [year] => 2013
    [name] => Array
        (
            [uploaded_file] => pic.jpg
        )

    [type] => Array
        (
            [uploaded_file] => image/jpg
        )

    [tmp_name] => Array
        (
            [uploaded_file] => /tmp/phpRqUUw2
        )

    [error] => Array
        (
            [uploaded_file] => 0
        )

    [size] => Array
        (
            [uploaded_file] => 1024
        )

)

我真正想要的是这个数组结构:

    Array
(
    [name] => A name
    [description] => A description
    [year] => 2013
    [uploaded_file] => Array (
        [name] => Array
            (
                [uploaded_file] => pic.jpg
            )

        [type] => Array
            (
                [uploaded_file] => image/jpg
            )

        [tmp_name] => Array
            (
                [uploaded_file] => /tmp/phpRqUUw2
            )

        [error] => Array
            (
                [uploaded_file] => 0
            )

        [size] => Array
            (
                [uploaded_file] => 1024
            )

    )
)

由于它是一个变量函数,我需要动态获取第二个键[uploaded_file]。

  1. 我如何获得第二把钥匙?
  2. 我如何获得所需的结构? 我玩了array_merge()和array_flip,但没有做任何工作。
  3. 非常感谢!

    更新: 这是合并代码:

    $data  = isset( $_POST[ $tab ] )  ? $_POST[ $tab ]  : array();
    $files = isset( $_FILES[ $tab ] ) ? $_FILES[ $tab ] : array();
    
    $result = array_merge($data, $files);
    

2 个答案:

答案 0 :(得分:1)

试试这个

$data  = isset( $_POST[ $tab ] )  ? $_POST[ $tab ]  : array();
$files = isset( $_FILES[ $tab ] ) ? $_FILES[ $tab ] : array();
foreach($files as $key => $value){
    $name[$key] = array($tab => $value);
}
$data[$tab] = $name;

// simply print the data of $data to get your output - just to show you
print_r($data);

答案 1 :(得分:0)

为什么不将$ _FILES数组值分配给新数组中的新键?

$files_data = array();
for (int i = 0; i < count($_POST['items']); i++) {
    // assuming each $_POST['items'] value is associated with each $_FILES value
    $item_data = $_POST['items'][i];
    $item_data['uploaded_file'] = $_FILES[i];
    $files_data[] = $item_data;
}