PHP array keys - how to display?
I'm doing some work with a Google Analytics class. I get output as below:
Array
(
[20090401] => Array
(
[ga:pageviews] => 5000
[ga:visits] => 2500
)
[20090402] =>开发者_如何学C; Array
(
[ga:pageviews] => 5000
[ga:visits] => 2500
)
etc. How do I get the data to display in a table with the first column showing the date? ie the key for each array element.
like this:
20090401-----5000-----2500
Try this:
<?php
foreach ($report as $date=>$item) {
print($date.'-----'.$item['ga:pageviews'].'-----'.$item['ga:visits']);
}
?>
The piece you were missing was assigning the optional variable for the key in your foreach
.
I'm not quite sure what you're asking but maybe this would help...
<?php
foreach($array as $key => $value)
{
echo $key . " => " . $value;
}
?>
Untested, but here's the idea...
foreach ( $report as $item => $data ) {
echo implode( '-----', array( $item, $data['ga:pageviews'], $data['ga:visits'] ) );
}
foreach($array AS $date => $data){
echo '
<tr>
<td>'.$date.'</td>
<td>'.$data['ga:pageviews'].'</td>
<td>'.$data['ga:visits'].'</td>
</tr>';
}
Check the php documentation about the foreach construct if you did not know about it.
The PHP function array_keys might help you out too: http://us.php.net/manual/en/function.array-keys.php
精彩评论