PHP - 创建并显示多维数组

3

我有这个XML文件:

<eSummaryResult>
    <DocSum>
        <Id>11482001</Id>
        <Item Name="PubDate" Type="Date">2001 Jun</Item>
        <Item Name="EPubDate" Type="Date" />
        <Item Name="Source" Type="String">Adverse Drug React Toxicol Rev</Item>
        <Item Name="AuthorList" Type="List">
            <Item Name="Author" Type="String">Mantle D</Item>
            <Item Name="Author" Type="String">Gok MA</Item>
            <Item Name="Author" Type="String">Lennard TW</Item>
        </Item>
        <Item Name="LastAuthor" Type="String">Lennard TW</Item>
        <Item Name="Title" Type="String">Adverse and beneficial effects of plant extracts on skin and skin disorders.</Item>
        <Item Name="Volume" Type="String">20</Item>
        <Item Name="Issue" Type="String">2</Item>
        <Item Name="Pages" Type="String">89-103</Item>
        <Item Name="LangList" Type="List">
            <Item Name="Lang" Type="String">English</Item>
        </Item>
        <Item Name="NlmUniqueID" Type="String">9109474</Item>
        <Item Name="ISSN" Type="String">0964-198X</Item>
        <Item Name="ESSN" Type="String" />
        <Item Name="PubTypeList" Type="List">
            <Item Name="PubType" Type="String">Journal Article</Item>
            <Item Name="PubType" Type="String">Review</Item>
        </Item>
        <Item Name="RecordStatus" Type="String">PubMed - indexed for MEDLINE</Item>
        <Item Name="PubStatus" Type="String">ppublish</Item>
        <Item Name="ArticleIds" Type="List">
            <Item Name="pubmed" Type="String">11482001</Item>
            <Item Name="eid" Type="String">11482001</Item>
            <Item Name="rid" Type="String">11482001</Item>
        </Item>
        <Item Name="History" Type="List">
            <Item Name="pubmed" Type="Date">2001/08/03 10:00</Item>
            <Item Name="medline" Type="Date">2002/01/23 10:01</Item>
            <Item Name="entrez" Type="Date">2001/08/03 10:00</Item>
        </Item>
        <Item Name="References" Type="List" />
        <Item Name="HasAbstract" Type="Integer">1</Item>
        <Item Name="PmcRefCount" Type="Integer">3</Item>
        <Item Name="FullJournalName" Type="String">Adverse drug reactions and toxicological reviews</Item>
        <Item Name="ELocationID" Type="String" />
        <Item Name="SO" Type="String">2001 Jun;20(2):89-103</Item>
    </DocSum>
</eSummaryResult>

我想创建这样一个数组:
$results2 = array(
    '0' => array(
        'id' => 'xxxxxxxx',
        'authors' => array(
            '0' => 'xxxxxxxxxx',
            '1' => 'xxxxxxxxxx',
            )
    ),
    '1' => array(
        'id' => 'xxxxxxxx',
        'authors' => array(
            '0' => 'xxxxxxxxxx',
            '1' => 'xxxxxxxxxx',
            )
    ),
);

我编写了一个函数,用于从XML文件中获取数据并在PHP中显示。我正在尝试使用以下结构来存储数据并进行显示,但由于对PHP语法不是很熟悉,所以遇到了一些问题。以下是该函数:

function esummary_query($db, $id) { 
    $context = stream_context_create(array(
      'http'=>array(
        'user_agent' => 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11'
       )
    ));

    $xml = file_get_contents('http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=' . $db . '&id=' . $id, FALSE, $context);

    $xml_file = simplexml_load_string($xml);
    $results2 = array();
    foreach ( $xml_file->DocSum as $items ) {
        $results2[]['id'] = $items->Id;
        $authors = $xml_file->xpath("//Item[@Name='Author']");
        foreach ($authors as $author) {
            $results2[]['authors'][] = $author;
        }
    }
    return $results2;
}


echo'<h3>id:</h3>' . $results2[0]['id'] . "<br> author:" . $results2[0]['authors'];

但是当我展示它时,只显示了id而没有作者的名字。print_r 展示如下:

Array ( [0] => Array ( [id] => SimpleXMLElement Object ( [0] => 11850928 ) ) [1] => Array ( [authors] => Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [Name] => Author [Type] => String ) [0] => LoPresti PJ ) ) ) [2] => Array ( [authors] => Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [Name] => Author [Type] => String ) [0] => Hambrick GW Jr ) ) ) )

谢谢大家!

每次执行 $results2[] 时,都会向 $results2 添加一个新元素... - Passerby
我尝试将 $results2[$i]['authors'][] = $author; 放入代码中,但似乎没有起作用。 - ThemesCreator
2个回答

0

添加计数器并将其用作数组键

function esummary_query($db, $id) { 
    $context = stream_context_create(array(
      'http'=>array(
        'user_agent' => 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11'
       )
    ));

    $xml = file_get_contents('http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=' . $db . '&id=' . $id, FALSE, $context);

    $xml_file = simplexml_load_string($xml);
    $results2 = array();
    $c=0;
    foreach ( $xml_file->DocSum as $items ) {           
        $results2[$c]['id'] = (string)$items->Id;
        $authors = $xml_file->xpath("//Item[@Name='Author']");
        foreach ($authors as $author) {
            $results2[$c]['authors'][] = (string)$author;
        }
        $c++;
    }
    return $results2;
}

例子输出

Array
(
    [0] => Array
        (
            [id] => 11482001
            [authors] => Array
                (
                    [0] => Mantle D
                    [1] => Gok MA
                    [2] => Lennard TW
                    [3] => Mantle D
                    [4] => Gok MA
                    [5] => Lennard TW
                )

        )

    [1] => Array
        (
            [id] => 11482001
            [authors] => Array
                (
                    [0] => Mantle D
                    [1] => Gok MA
                    [2] => Lennard TW
                    [3] => Mantle D
                    [4] => Gok MA
                    [5] => Lennard TW
                )

        )

)

0

你也可以尝试使用DOMDocument,它的学习曲线比SimpleXML陡峭,但一旦掌握了它,它提供的灵活性比SimpleXML更多。

$result = array();

// pretty output if it's needed        
$xml = new DOMDocument('1.0', 'utf-8');
$xml->preserveWhiteSpace = false;
$xml->formatOutput = true;

$source = file_get_contents('http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=' . $db . '&id=' . $id, FALSE, $context);
$xml->loadXML($source);

// xpath to use later
$xpath = new DOMXPath($xml);

// get all the nodes that we want to extract data from
$nodes = $xml->getElementsByTagName('DocSum');

foreach ($nodes as $node)
{
    // extract the ID
    $idNode = $node->getElementsByTagName('Id');

    $id = $idNode->item(0)->nodeValue;

    // extract the authors, we need to use xpath
    $query = '//Item[@Name="AuthorList"]/Item[@Name="Author"]';
    $authorNodes = $xpath->query($query, $node);

    $authors = array();
    foreach ($authorNodes as $authorNode)
    {
        $authors[] = $authorNode->nodeValue;
    }

    // add the found details to the result array
    $result[] = array(
        'id'      => $id,
        'authors' => $authors,
    );
}

输出就是你所需要的内容:

array
  0 => 
    array
      'id' => string '11482001' (length=8)
      'authors' => 
        array
          0 => string 'Mantle D' (length=8)
          1 => string 'Gok MA' (length=6)
          2 => string 'Lennard TW' (length=10)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接