如何在多维非关联数组上使用foreach循环 [英] How to use a foreach loop on a multidimensional non associative array
问题描述
我基本上将csv文件employee_data的行读入名为$ data的数组中
I basically read the rows of a csv file employee_data into an array called $data
$dataSrc = "persistence/employee_data.csv";
$dataFile = fopen($dataSrc, "r") or die("Unable to open file!");
$i=0; //index for the array
while (($data = fgetcsv($dataFile)) !== FALSE) {
//$data is an array of the csv elements
print_r($data);
}
fclose($dataFile);
当我将 $ data
数组中的元素插入到print_r函数中时,它们如下.
The elements within the $data
array when I inserted it into the print_r function are as follows.
Array ( [0] => JOHN WILLIAMS [1] => 6/8/1998 [2] => 55456434E [3] => 4321 )
Array ( [0] => SARAH JONES [1] => 15/01/1982 [2] => 56834645Q [3] => 1234 )
Array ( [0] => JAMES Brennan [1] => 09/05/1978 [2] => 25689514W [3] => 8575 )
此数组中有3个数组,但是该数组中的每个数组都没有单独的键.
There are 3 arrays in this array but there are no individual keys for each array in the array.
当我尝试遍历数组时,它给了我一个警告.
警告:为foreach()提供了无效的参数"
When I try to iterate through the array, it gives me a warning.
"Warning: Invalid argument supplied for foreach()"
我知道这样的数组
$food = array('Healthy'=>
array('Salad', 'Vegetables', 'Pasta'),
'Unhealthy'=>
array('Pizza','Ice cream'));
您将使用类似的方法来访问数组数组中的元素.
You would use something like this to access the elements within the array's of the array.
foreach($food as $element => $inner_array)
{
echo $element;
foreach($inner_array as $item)
{
echo $item;
}
}
这种方法不适用于我的 $ data
array
.您将如何获得对像 $ data
这样的数组的访问权?
This approach doesn't work for my $data
array
.
How would you approach gaining access to an array like $data
?
推荐答案
由于 fgetcsv()逐行读取,因此$ data始终包含雇员的最后记录,即单维数组.这里您需要将数据存储到另一个数组(制作多维数组)
Since fgetcsv() read row by row, so $data is always contain last record of employee which is single dimension array. here you need to store data to another array(making multidimensional array)
尝试一下...
$dataSrc = "persistence/employee_data.csv";
$dataFile = fopen($dataSrc, "r") or die("Unable to open file!");
$i=0; //index for the array
//creating $result array for storing each employee data.
$result = [];
while (($data = fgetcsv($dataFile)) !== FALSE) {
//assign each employee data to $result array. now result will be multidimensional array.
$result[] = $data;
}
fclose($dataFile);
您现在可以使用
foreach($result as $resultKey => $employees)
{
//display key of $result.
echo $resultKey;
foreach($employees as $data)
{
echo $data;
}
}
这篇关于如何在多维非关联数组上使用foreach循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!