5

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
1
  • 2
    Try this foreach ($leads as $key=>$country) { echo '<tr><td>' . $key . '</td><td>' . $country['TW'] . '</td><td>' . $country['LY'] . '</td><td>' . $country['LW'] . '</td></tr>'; } Commented Oct 8, 2012 at 14:10

3 Answers 3

7

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)

Sign up to request clarification or add additional context in comments.

Comments

3

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);
}

Comments

1

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>';
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.