输出多维数组

时间:2019-07-24 16:04:34

标签: php multidimensional-array

我有一个数组$myArr['words'],它存储这样的数据:

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 ....
    )
)

我需要这样说:

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

...每学期。这是我尝试过的:

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

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

但是,即使这样也不会输出术语列表。我想念什么?

1 个答案:

答案 0 :(得分:1)

foreach是您的朋友在这里。

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

这将依次获取数组中的每个元素,例如第一个循环将具有:

/*
[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 ...
     )
*/