Access multidimensional arrays of a php input

Asked

Viewed 142 times

0

I have several image arrays in the following format:

<input type="file" name="imagens[$id][]">

The $id is changed dynamically. How do I access to take some of the image data, the name for example, in php?

Updating:

Array
(
    [45] => Array
        (
            [0] => 1.jpg
            [1] => 2.jpg
            [2] => 
        )

    [44] => Array
        (
            [0] => 4.jpg
            [1] => 5.jpg
            [2] => 
        )

)

Solution: I was able to access it this way:

$_FILES['imagens']['name'][$id]
  • 1

    $_FILES['imagens'][0]['tmp_name'], in the doubt of a print_r($_FILES);

  • Uses a echo <pre>; with print_r($array); instead of var_dump, this bad to read.

  • Hello @Guilhermelautert , updated this way

2 answers

0

First note that in your array not the key name or tmp_name which is common when using $_FILES in PHP.

This way I know you must be using the wrong method to capture the form data. (You must be using $_POST).

Usually when you want to make one upload file(s), if used :

<form action="upload.php" enctype="multipart/form-data" method="post">
    <input type="file" name="imagens[$id][]">
</form>

Note that in the form this method="post", however in PHP you should capture it by $_FILES. What should generate an array like this :

Array
(
    [45] => Array
        (
            [0] => Array 
                (
                    [name] => 1.jpg
                    [type] => image/jpeg
                    [tmp_name] => /tmp/php/php6hst32
                    [size] => 98174
                )
            [1] => Array 
                (
                    [name] => 2.jpg
                    [type] => image/jpeg
                    [tmp_name] => /tmp/php/php6hst32
                    [size] => 98174
                )
        )

    [44] => Array
        (
            [0] =>  Array 
                (
                    [name] => 4.jpg
                    [type] => image/jpeg
                    [tmp_name] => /tmp/php/php6hst32
                    [size] => 98174
                )
        )
)

To manipulate your content you can use foreach:

foreach($_FILES as $id => $files){
    foreach($files as $k => $file){
        $name = $file['name'];
        $tmpName = $file['tmp_name'];

        printf("name : %s\n tmpName : %s", $name, $tmpName);
    }
}

0

Since you don’t know the value of the key, the ideal is to go through the array:

foreach($_FILES['imagens'] as $img){
   echo $img['tmp_name'];
}
  • Hello, I tried this way, but it does not recognize the index 'tmp_name'. I tested with var_dump, and it does not recognize any of the traditional file(name, size, etc) indexes. The indexes are all as number, I’ll paste what found.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.