PHP多维数组基于键提取特定值 [英] PHP Multidimensional Array Extract Specific Values Based Upon Key
问题描述
我正在尝试通过基于键提取特定的数组值来创建锚链接。我试过在for循环内使用foreach循环,但是似乎不起作用。
基于下面的多维数组,我如何遍历每个数组子数组以创建单个锚链接,例如:
示例:
/ *数组示例* /
array(3){
[0] =>
array(2){
[ @attributes] =>
array(1){
[ id] => string(1) 2
}
[ name] => string(10) Mark
}
[1] =>
array(2){
[ @attributes] =>
array(1){
[ id] => string(1) 4
}
[ name] => string(8) John
}
[2] =>
array(2){
[ @attributes] =>
array(1){
[ id] => string(1) 5
}
[ name] => string(10) Suzy
}
/ *所需输出* /
< a href = example.com?id=2&name=标记标记< / a>
< a href = example.com?id=4&name=john>约翰< / a>
< a href = example.com?id=5&name=mark> Suzy< / a>
假设您发布的数组是a的内容变量$ users。您可以执行以下操作来遍历它:
foreach($ users为$ usr)
{
$ usr ['@attributes'] ['id'];
$ usr [’name’];
}
这样,您可以遍历每个节点而不必担心索引。 / p>
您可以通过几种方式在每个foreach迭代中输出链接。一个完整的示例(允许使用HTML而不必转义每个特殊字符)可以是:
<?php
foreach($ users as $ usr)
{?>
< a href = example.com?id=<?php echo $ usr ['@ attributes'] ['id'];?>& name =<?php echo $ usr [ 'name'];?>><?php echo $ usr ['name']; < / a>
<?php}?>
虽然它看起来很复杂,但带有许多PHP的打开和关闭标签,但在标记,几乎没有性能损失
I'm trying to create an anchor link by extracting specific array values based upon based upon the key. I've tried using a foreach loop inside of a for loop, however that doesn't seem to work.
Based upon the below multidimensional array how can I loop through each subarray to create individual anchor links, such as:
Example:
/* Array Example */
array(3) {
[0]=>
array(2) {
["@attributes"]=>
array(1) {
["id"] => string(1) "2"
}
["name"]=> string(10) "Mark"
}
[1]=>
array(2) {
["@attributes"]=>
array(1) {
["id"]=> string(1) "4"
}
["name"]=> string(8) "John"
}
[2]=>
array(2) {
["@attributes"]=>
array(1) {
["id"]=> string(1) "5"
}
["name"]=> string(10) "Suzy"
}
/* Desired Output */
<a href="example.com?id=2&name=mark"> Mark </a>
<a href="example.com?id=4&name=john"> John </a>
<a href="example.com?id=5&name=mark"> Suzy </a>
Let's assume the array you posted is the content of a variable called $users. You can walk through it by doing
foreach ($users as $usr)
{
$usr['@attributes']['id'];
$usr['name'];
}
This way, you can go through every node without worrying about the indexes.
You may output the link on each foreach iteration in several ways. A complete example (which allows to use HTML without escaping every special character) could be:
<?php
foreach ($users as $usr)
{ ?>
<a href="example.com?id=<?php echo $usr['@attributes']['id']; ?>&name=<?php echo $usr['name']; ?>"><?php echo $usr['name']; ?></a>
<?php } ?>
While it looks complex, with a lot of PHP opening and closing tags, it makes it easier on the markup with almost no performance penalty
这篇关于PHP多维数组基于键提取特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!