使用foreach而不是print_r

时间:2017-11-03 14:41:01

标签: php foreach

我有一行代码来获取属性:

$attributes = $as->getAttributes();

当我使用print_r

$results = print_r($attributes);

这就是我得到的:

Array
(
    [http://schemas.microsoft.com/2012/12/certificatecontext/extension/subjectkeyidentifier] => Array
        (
            [0] => username
        )

    [http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress] => Array
        (
            [0] => email@mail.com
        )

    [http://schemas.xmlsoap.org/claims/CommonName] => Array
        (
            [0] => User lastname
        )

    [http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn] => Array
        (
            [0] => email@mail.com
        )

    [uid] => Array
        (
            [0] => user
        )

)

如何使用foreach显示这些结果?

2 个答案:

答案 0 :(得分:1)

获取所有可以使用的信息

foreach($attributes as $url=>$info) 
{
   echo $url; //example : http://schemas.microsoft.com/2012/12/certificatecontext/extension/subjectkeyidentifier
   foreach($info as $key=>$attr)
   {
      echo $key; //example : 0
      echo $attr; //example : username
   }
}

答案 1 :(得分:1)

根据您对评论的回答,您希望能够以不同方式格式化每一行。因此,您可以执行以下操作:

<?php
foreach($attributes as $key => $value){
    echo $key; // the key of the array
    echo $value; // the value of the array row
    echo '<br />'; // if you want a new line
}

但是,如果您想要一种通用格式,例如列表,则可以使用implode为您执行此操作(docs)。

<?php
echo '<ul><li>'; // Open list and add first open tag
echo implode('</li><li>', $attributes);
echo '</li></ul>'; //Close last item and list element

这会生成一个HTML格式的元素列表,但你当然可以做任何适用于你的项目的分隔符。