本文介绍了如何转置多维多文件上传提交并维护关联键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下形式,当发送多张图像时生成一个多维数组,所有数据默认排序.

I have the following form that when sending multiple images generates a multidimensional array with all the data ordered by default.

表单 HTML 和 PHP:

<html>
    <body>
        <form enctype="multipart/form-data" action="" method="POST">
            <input name="image[]" type="file" multiple />
            <input type="submit" name="send" value="Send" />
        </form>
    </body>
</html>

发送它会生成一个这样的数组:

$file1 = array(
    'imagen' => array(
        'name'      => array(
            'Image_name',
            'Image_name'
        ),
        'type'      => array(
            'jpg',
            'jpg'
        ),
        'tmp_name'  => array(
            'jpg',
            'jpg'
        ),
        'error'     => array(
            0,
            0
        ),
        'size'      => array(
            '200',
            '200'
        )
    )
);

我需要以更简单的方式重构这个数组,以便将各个图像值放在一起.

I need to restructure this array in a simpler way so that the respective image values are together.

预期输出:

$file2 = array(
    array(
        'name' => 'Image_name',
        'type' => 'jpg',
        'tmp_name' => 'jpg',
        'error' => 0,
        'size' => 200
    ),
    array(
        'name' => 'Image_name',
        'type' => 'jpg',
        'tmp_name' => 'jpg',
        'error' => 0,
        'size' => 200
    )
);

推荐答案

此任务是关于转置"数组和维护关联键.

This task is about "transposing" an array and maintaining associative keys.

三年后,我决定大修/重写这个答案,因为编码标准比我现在能容忍的要低得多,而且通常有太多的噪音.我只有两种方法可以在我自己的一个项目中执行此任务.两者都提供相同的(期望的)结果;将它们分开的只是编码风格的问题.

Three years later, I have decided to overhaul/rewrite this answer because the coding standard was much lower than I now tolerate and there was generally too much noise. There are only two ways that I would perform this task on one of my own projects. Both provide the same (desired) result; it is only a matter of coding style that divides them.

演示

$POST = [
    'image' => [
        'name' => ['Image_name1', 'Image_name2'],
        'type' => ['jpg', 'png'],
        'tmp_name' =>['jpg', 'png'],
        'error'    => [0, 0],
        'size'     => ['200', '300']
    ]
];

函数式编程:

$keys = array_keys($POST['image']);
var_export(
    array_map(
        function(...$col) use ($keys) {
            return array_combine($keys, $col);
        },
        ...array_values($POST['image'])
    )
);

语言结构语法:

foreach ($POST['image'] as $key => $entries) {
    foreach ($entries as $index => $entry) {
        $result[$index][$key] = $entry;
    }
}
var_export($result);

这篇关于如何转置多维多文件上传提交并维护关联键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 16:21