如何在PHP中按子数组值对多维数组进行分组并重新分配键
我查看了所有类似的问题和示例(有很多),但仍然无法实现这一点(尽管我认为我很接近) 我有一个从文本文件中提取的员工日程表数组 schedule.txt: 123,Joe,20120208,0845,1645 123,Joe,20120209,0800,1600 456,Sue,20120208,0900,1700 456,Sue,20120209,0700,1500 ... 123,乔,2012020848451645 123,乔,2012020908001600 456,苏,2012020809001700 456,苏,2012020907001500 ... 我生成数组的代码是: $schedule = file_get_contents('./schedule.txt'); $s = explode("\n", $schedule); for ($i = 0; $i < count($s); $i++) { $s[$i] = explode(",", $s[$i]); } print_r($s); $schedule=file_get_contents('./schedule.txt'); $s=分解(“\n”,$schedule); 对于($i=0;$i如何在PHP中按子数组值对多维数组进行分组并重新分配键,php,multidimensional-array,grouping,Php,Multidimensional Array,Grouping,我查看了所有类似的问题和示例(有很多),但仍然无法实现这一点(尽管我认为我很接近) 我有一个从文本文件中提取的员工日程表数组 schedule.txt: 123,Joe,20120208,0845,1645 123,Joe,20120209,0800,1600 456,Sue,20120208,0900,1700 456,Sue,20120209,0700,1500 ... 123,乔,2012020848451645 123,乔,2012020908001600
这给了我正确的输出,但我现在得到了未定义的偏移量错误。另外,如果子数组中的键数发生变化,则此代码现在仅限于我显式输入的4个…如果我理解正确,这应该足够了:)
您可以使用:
$handle=fopen('./schedule.txt',r');
$employees=array();
而($line=fscanf($handle,'%d,%s')){
$employees[$line[0]][]=分解(',',$line[1]);
}
fclose($handle);
打印(员工);
有一个调用的函数,可以轻松获取逗号分隔的值。没必要自己做
此代码还可以解决您的问题并正确处理空行:
if (($handle = fopen("schedules.csv", "r")) !== FALSE) {
$schedules = array();
while (($data = fgetcsv($handle)) !== FALSE) {
if ($data[0] !== null) { //blank lines return an array containing null
$schedules[$data[0]][] = array_slice($data, 1);
}
}
fclose($handle);
//do what you need to
} else {
// file failed to open
}
注意,我将文件命名为.csv
,而不是.txt
。我建议您将逗号分隔的值保存为.csv
文件。甚至可以定义文件中每列的内容
<?php
//read the file into an array with each line being an entry
$schedule = file('./schedule.txt');
//empty array
$s = array();
//loop through file lines
foreach($schedule as $row){
//explode on comma
$row = explode(",", trim($row));
//if the id doesn't exist yet...
if(!isset($s[$row[0]])){
//...make it an empty array
$s[$row[0]] = array();
}
//add the row under the id
$s[$row[0]][] = $row;
}
print_r($s);
?>
if (($handle = fopen("schedules.csv", "r")) !== FALSE) {
$schedules = array();
while (($data = fgetcsv($handle)) !== FALSE) {
if ($data[0] !== null) { //blank lines return an array containing null
$schedules[$data[0]][] = array_slice($data, 1);
}
}
fclose($handle);
//do what you need to
} else {
// file failed to open
}