katie hudson
katie hudson

Reputation: 2893

Obtaining data from an array

I have the variable $fileData which contains the following array

array:2 [▼
  "folder1" => array:2 [▼
    0 => "something.png"
    1 => "something.png"
  ]
  "folder2" => array:2 [▼
    0 => "something.png"
    1 => "something.png"
  ]
]

What I am trying to do is add the folder names (folder1 and folder2) as select options. I am doing some testing and for some reason I am finding it difficult to access the folder names. If I do

foreach($fileData as $data) {
    var_dump($data);
}

It will output the actual content of folder1 and folder2 e.g.

array:2 [▼
  0 => "something.png"
  1 => "something.png"
]

So how would I go about getting the actual folder names without knowing what these names are?

Thanks

Upvotes: 1

Views: 43

Answers (2)

Poiz
Poiz

Reputation: 7617

You can just loop through the Array using foreach Looping Construct and then build your Select <option> accordingly like so:

<?php

$arrPix     =  [
      "folder1" =>[
        0 => "something.png",
        1 => "something.png",
      ],
      "folder2" => [
        0 => "something.png",
        1 => "something.png",
      ]
];
$select = "<select name='img_folders' id='img_folder' class='form-control img_folders'>" . PHP_EOL;

foreach($arrPix as $folderName=>$arrImg){
    $select .="<option name='{$folderName}'>{$folderName}</option>option";
}
$select .= "</select>" . PHP_EOL;

echo $select;

Upvotes: 1

RiggsFolly
RiggsFolly

Reputation: 94662

You need to access the name(index) of each occurance the first array so use the foreach with both as parameters like this

foreach($fileData as $folder => $files) {
    echo "Folder name is $folder\n";
    foreach($files as $file) {
        echo "....Contains $file\n";
    }
}

Upvotes: 3

Related Questions