我的数组包括:
Array (
[**Anconia**] => Array ( [1335372330] => 7 [1335190784] => 7 [1334883979] => 7 [1334672871] => 7 [1334539093] => 7 [1334337930] => 7 [1334189033] => 7 [1334007668] => 7 [1333567097] => 7 [1332973327] => 7 [1332533799] => 7 [1332215655] => 7 [1331697329] => 7 [1331239651] => 7 [1331075294] => 7 [1330983800] => 7 [1330658201] => 7 [1330484662] => 7 [1330202828] => 7 [1330028992] => 7 )
[**Angellica**] => Array ( [1335372330] => 9 [1335190784] => 9 [1334883979] => 10 [1334539093] => 10 [1334337930] => 10 [1334189033] => 10 [1334007668] => 10 [1331697329] => 9 [1331239651] => 9 [1331075294] => 9 [1330983800] => 9 [1330658201] => 10 [1330484662] => 10 [1330202828] => 8 [1330028992] => 9 )
)
TimeStamp Tally Number
[1335372330] => 7
在尝试提取时,使用foreach使我感到困惑。想要打印NAME(以粗体显示)并显示时间戳=多少。
我该怎么做?
提前致谢!
编辑:
我的尝试
foreach($results as $k => $v) {
$THEAD .= "<th scope='col'>".$k."</th>";
$TBODY .= "<tr><th scope='row'>".$v."</th>";
$TBODY2 .= "<td>".$results[$k]."</td>";
}
答案 0 :(得分:2)
通常,您可以循环遍历嵌套数组,方法与循环单级数组相同。例如:
$myArray = array(
'first-level-first-key' => array(
'second-level-first-key' => 'some value',
'second-level-second-key' => 'another value'
),
'first-level-second-key' => array(
'seond-level-another-key' => 'yet another value'
)
);
foreach($myArray as $first_level_key => $first_level_value) {
echo 'Key: '. $first_level_key .'<br />';
echo 'Values: ';
foreach($first_level_value as $second_level_key => $second_level_value) {
echo $second_level_value .', ';
}
echo '<br /><br />';
}
这将打印出来:
Key: first-level-first-key
Values: some value, another value,
Key: first-level-second-key
Values: yet another value,
现在您知道如何遍历嵌套数组。玩得开心!
修改强>
更多解释,作为对以下tmyie评论的回答: 正如您所看到的,每个元素本身都是一个数组:
$myArray['first-level-first-key'] = array('second-level-first-key' => ... );
第一个foreach遍历所有'first-level'数组(在我的例子中是带有'first-level -....'键的元素)。因此,在该循环中,变量$first_level_value
包含一个数组。第二个foreach遍历 ,第二级数组。如果你在第二级元素中保存了另一个数组,那么这种循环嵌套实际上是无穷无尽的。
将它与你面前的几个盒子进行比较。在第一个循环中,您说“打开我前面的每个盒子”。然后,对于你打开的每个方框,嵌套循环显示'打开我在该框中找到的每个框',依此类推。
虽然你的应用程序设计很可能是非常错误的,如果你写这个,下面的例子是完全有效的:
foreach($myArray as $x) {
foreach($x as $y) {
foreach($y as $z) {
foreach($z as $p) {
// etc
}
}
}
}
答案 1 :(得分:1)
由于$v
是您foreach
中的另一个数组,因此您需要执行另一个foreach
:
foreach($results as $k => $v) {
foreach($v as $timestamp => $tally) {
// do whatever you want
}
}
我没有给你一个完整的代码,而是希望将其作为练习留给你,但这就是 - 根据你的问题 - 提取多维数组
答案 2 :(得分:1)
你可以试试这个
<?php
echo '<table>';
echo ' <tr>';
echo ' <th>Time Stamp</th>';
echo ' <th>Tally </th>';
echo ' </tr>';
foreach($myArray as $timeStampArray)
{
foreach($timeStampArray as $timestamp => $tally)
{
echo ' <tr>';
echo ' <td>'.$timestamp .'</td>';
echo ' <td>'.$tally.' </td>';
echo ' </tr>';
}
}
echo '</table>';
?>