我试图在关联数组上使用foreach循环创建一个html表。这是关于数组的更多细节。
$assoc_array = array(
"0" => array(
"project_id" => "1",
"emp_id" => "123",
"emp_name" => "Max",
"project" => "Java"
),
"1" => array(
"project_id" => "2",
"emp_id" => "123",
"emp_name" => "Max",
"project" => "Java"
),
"2" => array(
"project_id" => "3",
"emp_id" => "124",
"emp_name" => "Max",
"project" => "Java"
),
"3" => array(
"project_id" => "4",
"emp_id" => "124",
"emp_name" => "Max",
"project" => "Java"
),
"4" => array(
"project_id" => "5",
"emp_id" => "125",
"emp_name" => "Max",
"project" => "Java"
),
"5" => array(
"project_id" => "6",
"emp_id" => "125",
"emp_name" => "Max",
"project" => "Java"
)
)
?>
所以我试图用他们的emp_id对它们进行分组。为此,我试图使用下面的逻辑
$assoc_array = array(
"0" => array(
"project_id" => "1",
"emp_id" => "123",
"emp_name" => "Max",
"project" => "Java"
),
"1" => array(
"project_id" => "2",
"emp_id" => "123",
"emp_name" => "Max",
"project" => "Java"
),
"2" => array(
"project_id" => "3",
"emp_id" => "124",
"emp_name" => "Anna",
"project" => "Angular"
),
"3" => array(
"project_id" => "4",
"emp_id" => "124",
"emp_name" => "Anna",
"project" => "PHP"
),
"4" => array(
"project_id" => "5",
"emp_id" => "125",
"emp_name" => "John",
"project" => "Java"
),
"5" => array(
"project_id" => "6",
"emp_id" => "125",
"emp_name" => "John",
"project" => "Java"
)
);
$prevEmpid = '';
$tableData = '';
$tableStartTag = "
$tableEndTag = "
";$wholeData = "";
$trFixed = "
project id emp id emp nameproject";foreach($assoc_array as $val) {
if($val['emp_id'] !== $prevEmpid ) {
if($tableData) {
$wholeData = $tableStartTag . $trFixed . $tableData . $tableEndTag;
echo $tableData;
}
$wholeData = '';
$tableData = '';
$prevEmpid = $val['emp_id'];
}
$tableData .= "
" . $val['project_id'] . "". "
" . $val['emp_id'] . "". "
" . $val['emp_name'] . "". "
" . $val['project'] . "";}
但问题是,我没有得到最后一个表数据,因为foreach循环中的元素会通过其他条件。
任何小帮助都非常感谢。