Home > OS >  How to make a array inside array?
How to make a array inside array?

Time:05-14

I have this two array. I want to make a array inside an array like this. How can I achieve that. Code posted below. This is the image I am sending inside fileToUpload. The array I have

Array
(
    [fileToUpload] => Array
        (
            [name] => KERINOX COFFEE.jpg
            [type] => image/jpeg
            [tmp_name] => /opt/lampp/temp/phpuk5Uyo
            [error] => 0
            [size] => 2440617
        )

)

The array I want

Array
(
    [fileToUpload] => Array
        (
            [name] => Array
                (
                    [0] => KERINOX COFFEE.jpg
                )

            [type] => Array
                (
                    [0] => image/jpeg
                )

            [tmp_name] => Array
                (
                    [0] => /opt/lampp/temp/php0LlvE2
                )

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

            [size] => Array
                (
                    [0] => 2502103
                )

        )

)

CodePudding user response:

You can simply use array_map for this, to wrap each element into another array:

$data['fileToUpload'] = array_map(
  function($item) {
    return [$item];
  },
  $data['fileToUpload']
);

CodePudding user response:

Easy enough to build a new array:

$array = [
    'fileToUpload' => [
        'name' => 'KERINOX COFFEE.jpg',
        'type' => 'image/jpeg',
        'tmp_name' => '/opt/lampp/temp/phpuk5Uyo',
        'error' => 0,
        'size' => 2440617
    ]
];
$newArray = ['fileToUpload' => []];

foreach ($array['fileToUpload'] as $key => $value)
    $newArray['fileToUpload'][$key][] = $value;

CodePudding user response:

 $myArray = [];
 $myArray['fileToUpload']['name'] = array("file name");
 $myArray['fileToUpload']['type'] = array("file type");
 $myArray['fileToUpload']['tmp_name'] = array("temporary name");
 $myArray['fileToUpload']['error'] = array("error");
 $myArray['fileToUpload']['size'] = array("file size");

 echo "<pre>";
 print_r($myArray);

Output

  • Related