构建一个关联数组

时间:2011-07-30 17:09:30

标签: php associative-array

这将是我第一次构建关联数组。如果有人能帮助我,我将不胜感激。

基本上,我想循环遍历XML文件的目录。我想知道某个编辑器是否是该文件的编辑器,如果查询是真的,我想获取两条信息,并获得一个关联数组的结果,其中包含每个案例的两条信息找到编辑的名字。

所以这就是我到目前为止所得到的:

function getTitleandID($editorName) {

    $listofTitlesandIDs = array();

    $filename = readDirectory('../editedtranscriptions');

        foreach($filename as $file)
           {

           $xmldoc = simplexml_load_file("../editedtranscriptions/$file");
            $xmldoc->registerXPathNamespace("tei", "http://www.tei-c.org/ns/1.0");

   if ($editorName == $xmldoc->xpath("//tei:editor[@role='PeerReviewEditor']/text()"))
    {
    $title = $xmldoc->xpath("//tei:teiHeader/tei:title[1]");
    $id = $xmldoc->xpath("//tei:text/tei:body/tei:div/@xml:id[1]");

    $listofTitlesandIDs[] = //I don't know what to do here
    }
   else
    {
    $listofTitlesandIDs = null;
    }
}
return $listofTitlesandIDs
}

这是关于我陷入困境的地方。我希望能够将$listofTitlesandIDs作为关联数组,我可以调用两个不同键的值,例如: $listofTitlesandIDs['title']$listofTitlesandIDs[$id]

所以就是这样。我很感激您有时间提供任何帮助。

2 个答案:

答案 0 :(得分:1)

嗯,我确定这有点笨拙(业余爱好者的结果),但它给了我想要的结果。

function getTitlesandIDs($EditorName) //gets titles and IDs for given author
{
$list = array();
$filename = readDirectory('../editedtranscriptions');
foreach($filename as $file)
 {

    $xmldoc = simplexml_load_file("../editedtranscriptions/$file");
    $xmldoc->registerXPathNamespace("tei", "http://www.tei-c.org/ns/1.0");

    $title = $xmldoc->xpath("//tei:teiHeader/tei:fileDesc/tei:titleStmt/tei:title[1]");
    $id = $xmldoc->xpath("//tei:text/tei:body/tei:div/@xml:id");
    $editorName = $xmldoc->xpath("//tei:editor[@role='PeerReviewEditor']/text()")

    if ($editorName[0] == "$EditorName")
    {
    $result = array("title"=>$title[0], "id"=>$id[0]);

    $list[] = $result;
    }
}
return $list;
}

有了这个,我可以调用函数$list = getTitlesandIDs('John Doe'),然后访问每个实例的关联数组中的title和id。像这样:

foreach ($list as $instance)
    {
        echo $instance['title'];
        echo $instance['id'];
    }

也许有一天这会对某人有所帮助 - 如果你有任何关于让它更优雅的建议,请告诉我。

答案 1 :(得分:0)

$listofTitlesandIDs[$id] = $title;

你应该使用foreach循环遍历数组。