我对 PHP 比较陌生,希望你能帮我解决我的问题。我正在从数据库中选择数据到一个数组中以进行计时。最终,我想计算给定客户在项目上花费的总小时数。
这是填充多维数组的代码:...
foreach ($record as $data) {
$mArray = array();
$name = $data['user'];
$customer = $data['customer'];
$project = $data['project'];
$hours = $data['hours'];
$mArray[$name][$customer][$project] += $hours;
}
...
我现在想遍历 $mArray 以生成这样的 xml 文件:
...
foreach ($mArray as $username) {
foreach ($mArray[$username] as $customerName) {
foreach ($mArray[$username][$customerName] as $project ) {
echo '<'.$username.'><'.$customerName.'><'.$project.'><hours>'.
$mArray[$username][$customerName][$project].'</hours></'.$project.'>
</'.$customerName.'></'.$username.'>';
}
}
}
这个嵌套的 foreach 不起作用。有人可以给我一些关于如何遍历这个结构的提示吗?感谢您的阅读!
更新:根据我目前收到的评论(感谢大家),我有:
foreach ($mArray as $userKey => $username) {
foreach ($mArray[$userKey] as $customerKey => $customerName) {
foreach ($mArray[$userKey][$customerKey] as $projectKey => $projectName) {
echo '<name>'.$userKey.'</name>';
echo "\n";
echo '<customerName>'.$customerKey.'</customerName>';
echo "\n";
echo '<projectName>'.$projectKey.'</projectName>';
echo "\n";
echo '<hours>'.$mArray[$userKey][$customerKey][$projectKey].'</hours>';
echo "\n";
}
}
}
现在只提供一次迭代(一行数据)。