从数组中获取数据

时间:2016-07-14 15:56:01

标签: php arrays

我有变量$ fileData,其中包含以下数组

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

我要做的是添加文件夹名称(folder1和folder2)作为选择选项。我正在做一些测试,由于某种原因,我发现很难访问文件夹名称。 如果我做

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

它将输出folder1和folder2的实际内容,例如

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

那么如何在不知道这些名称的情况下获取实际的文件夹名称呢?

由于

2 个答案:

答案 0 :(得分:3)

你需要访问第一个数组的每个出现的名称(索引),所以使用带有as这样的foreach($fileData as $folder => $files) { echo "Folder name is $folder\n"; foreach($files as $file) { echo "....Contains $file\n"; } } 参数的foreach

public class UnitOfWork : IUnitOfWork
{
    private readonly ApplicationDbContext _context;

    private ICourseRepository _courses = null;
    private IStudentRepository _students = null;

    public UnitOfWork(ApplicationDbContext context)
    {
        _context = context;
    } 
  public ICourseRepository Courses => _courses ?? (_courses = new CourseRepository(_context));
public IStudentRepository Students => _students ?? (_students = new StudentRepository(_context));

答案 1 :(得分:1)

您可以使用foreach循环构造循环遍历数组,然后相应地构建您的选择<option>

<?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;