PHP 获取数组值和数组键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5745582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:21:50  来源:igfitidea点击:

PHP get both array value and array key

phparrayskey

提问by Francisc

I want to run a for loop through an array and create anchor elements for each element in the array, where the key is the text part and the value is the URL.

我想通过数组运行 for 循环并为数组中的每个元素创建锚元素,其中键是文本部分,值是 URL。

How can I do this please?

请问我该怎么做?

Thank you.

谢谢你。

回答by Marek Karbarz

This should do it

这应该做

foreach($yourArray as $key => $value) {
    //do something with your $key and $value;
    echo '<a href="' . $value . '">' . $key . '</a>';
}

Edit: As per Capsule's comment - changed to single quotes.

编辑:根据 Capsule 的评论 - 更改为单引号。

回答by DrupalFever

For some specific purposes you may want to know the current key of your array without going on a loop. In this case you could do the following:

出于某些特定目的,您可能想知道数组的当前键而不进行循环。在这种情况下,您可以执行以下操作:

reset($array);
echo key($array) . ' = ' . current($array);

The above example will show the Key and the Value of the first record of your Array.

上面的示例将显示数组的第一条记录的键和值。

The following functions are not very well known but can be pretty useful in very specific cases:

以下函数不是很出名,但在非常特定的情况下可能非常有用:

key($array);     //Returns current key
reset($array);   //Moves array pointer to first record
current($array); //Returns current value
next($array);    //Moves array pointer to next record and returns its value
prev($array);    //Moves array pointer to previous record and returns its value
end($array);     //Moves array pointer to last record and returns its value

回答by Karl Laurentius Roos

Like this:

像这样:

$array = array(
    'Google' => 'http://google.com',
    'Facebook' => 'http://facebook.com'
);

foreach($array as $title => $url){
    echo '<a href="' . $url . '">' . $title . '</a>';
}

回答by Capsule

In a template context, it would be:

在模板上下文中,它将是:

<?php foreach($array as $text => $url): ?>
    <a href="<?php echo $url; ?>"><?php echo $text; ?></a>
<?php endforeach; ?>

You shouldn't write your HTML code inside your PHP code, hence avoid echoing a bunch of HTML.

您不应该在 PHP 代码中编写 HTML 代码,从而避免回显一堆 HTML。

This is not filtering anything, I hope your array is clean ;-)

这不是过滤任何东西,我希望你的数组是干净的 ;-)