santa
santa

Reputation: 12512

Output multidimentional array

I have an array $myArr['words'] that stores data like this:

Array (
    [above-the-fold] => Array
    (
        [term] => Above the fold
        [desc] => The region of a Web ...
    )

    [active-voice] => Array
    (
        [term] => Active voice
        [desc] => Makes subjects do ...
    )

    [anchor-links] => Array
    (
        [term] => Anchor links
        [desc] => Used on content ....
    )
)

I need to out put it like this:

echo '
<a href="#'.$myArr['above-the-fold].'">
    '.$myArr['above-the-fold]['term'].'
</a>';

... for each term. Here's what I've tried:

$arrLen = count($myArr['words']);

for ($i = 0; $i < $arrLen; $i++) {
    foreach ($myArr['words'][$i] as $trm => $dsc) {
        echo $trm;
    }
}

But even this does not output the list of terms. What am I missing?

Upvotes: 0

Views: 32

Answers (1)

lufc
lufc

Reputation: 2040

foreach is your friend here.

foreach($myArr['words'] as $k => $v) {
    echo '
    <a href="#'.$k.'">
        '.$v['term'].'
    </a>';
}

This takes each of the elements in your array in turn, e.g. the first loop will have:

/*
[above-the-fold] => Array
(
    [term] => Above the fold
    [desc] => The region of a Web ...
)

So: 

$k = 'above-the-fold'
$v = Array
     (
        [term] => Above the fold
        [desc] => The region of a Web ...
     )
*/

Upvotes: 1

Related Questions