I have a quick question that I just can't seem to figure out even though it should be straightforward.
I have an associative array of the following structure:
[uk] => Array
(
[TW] => 1588
[LY] => 12936
[LW] => 13643
)
I am displaying it in an HTML table as follows.
foreach ($leads as $country) {
echo '<tr><td>' . $country . '</td><td>' . $country['TW'] . '</td><td>' . $country['LY'] . '</td><td>' . $country['LW'] . '</td></tr>';
}
but the country comes out as Array
so I'm just wondering what I am doing wrong to get the uk
part out.
Output
Array 1588 12936 13643
Use something like:
foreach ($leads as $name => $country) {
echo '<tr><td>' . $name. '</td><td>' . $country['TW'] . '</td><td>' . $country['LY'] . '</td><td>' . $country['LW'] . '</td></tr>';
}
Now, $name
in the loop is the key (in this case 'uk') and $country
is the value of the element, in this case the array (TW => 1588, LY => 12936, LW => 13643)
If you want to get the key of the item you're looping through, you need to use a different foreach
syntax:
foreach($leads as $code=>$country) {
var_dump($code,$country);
}
You need to extract the array key for each $country item. Add it to foreach.
foreach ($leads as $key => $country) {
echo '<tr><td>' . $key . '</td><td>' . $country['TW'] . '</td><td>' . $country['LY'] . '</td><td>' . $country['LW'] . '</td></tr>';
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.