dongmiao260399 2018-08-24 20:23
浏览 95
已采纳

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>
  • 写回答

1条回答 默认 最新

  • dsuxcxqep31023992 2018-08-24 20:35
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看