如何编写foreach循环,使用以下多维数组打印所有信息而不使用任何函数:
$workers = array(
"Natalie" => array
("First term" => array(
"Subworker" => "Susan",
"Length" => '1900-2000',
"Notes" => "Finished all tasks"),
"Second term" => array(
"Subworker" => "Laura",
"Length" => '1985-1986'),
),
"Laura" => array(
"First term" => array(
"Subworker" => "Sarah",
"Length" => '1999-1992'),
),
"Carolyn" => array(
"First term" => array(
"Subworker" => "Jenny",
"Length" => '1900 -1945',
"Notes" => array
("Finished all tasks",
"Did not finish all tasks",
"Completed partial tasks" )
),
),
"Jacob" => array(
"First term" => array(
"Subworker" => "Danielle",
"Length" => '1993-1994',
"Notes" => "Finished all tasks"),
),
"Jenny" => array(
"First term" => array(
"Subworker" => "Angela",
"Length" => '1999 - 2001'),
"Second term" => array(
"Subworker" => array(
"Paula" => "Let Go",
"Steve" => "Hired"),
"Length" => '1987 - 1999',
"Notes" => "Hired"),
)
);
/ ****到目前为止,我已经完成了以下操作,但它并没有打印出所有内容。例如,它不是在Jenny,第二学期,Subworker Paula和Steve下打印出来的./*****
foreach($workers as $worker => $value) {
foreach ($value as $newkey => $info) {
echo $worker.':<br>'.$newkey.':<br>';
foreach ($value as $newkey) {
echo 'Subworker: '.$newkey["Subkey"].'<BR>';
foreach ($value as $newkey) {
echo 'Length: '.$newkey["Length"].'<BR>';
foreach ($value as $newkey) {
echo 'Notes: '.$newkey["Notes"].'<BR>';
}
}
}
}
}
答案 0 :(得分:0)
有必要通过函数进行交叉并在上游进行小测试,避免在dev环境中返回错误总是有用的。 :)
我必须添加列表(ul,li)以便更好地阅读
if (is_array($workers) && !empty($workers)) {
echo loopArray($workers);
} else {
echo "<ul><li>".$workers."</li></ul>";
}
function loopArray($array)
{
$result = "";
$result .= "<ul>";
foreach ($array as $item => $value) {
if (is_array($value) && !empty($value)) {
$result .= "<li>".$item;
$result .= loopArray($value)."</li>";
} else {
$result .= "<ul><li>".$item.': '.$value."</li></ul>";
}
}
$result .= "</ul>";
return $result;
}
答案 1 :(得分:0)
要打印您提供的特定数组,而不使用函数:
// workers
foreach($workers as $worker => $workerarr) {
echo $worker.":<ul>\n";
// worker terms
foreach ($workerarr as $term => $terminfo) {
echo "<li>$term:<ul>\n";
// term info
foreach ($terminfo as $type => $typevalue) {
echo "<li>$type: ";
// is type value an array?
if ( is_array($typevalue) ) {
// if so, put in list
echo "<ul>\n";
foreach ($typevalue as $label => $value) {
$label = is_int($label)? '': "$label: "; // only print text
echo "<li>$label$value</li>\n";
}
echo "</ul>";
}
// if not...
else {
echo $typevalue;
}
echo "</li>\n";
}
echo "</ul></li>\n";
}
echo "</ul>";
}
使用无序列表帮助以可读方式显示信息。要查看问题中仅包含拆分标记,请参阅PHP Sandbox - Original