开发者

building an associative array

This is going to be my first time building an associative array. And if anyone can help me I would be grateful.

Basically, I want to loop through a directory of XML files. I want to find out if a certain editor was the editor of this file, and if the query is true, I would like to grab two pieces of information and achieve the result of an associate array with those two pieces of information for every case where the editor's name is found.

So here's what I have got so far:

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
}

This is about where I get stuck. I'd like to be able have $listofTitlesandIDs as an associative array where I could call up the values for two 开发者_开发知识库different keys, e.g. $listofTitlesandIDs['title'] and $listofTitlesandIDs[$id]

So that's about it. I'm grateful for any help you have time to provide.


Well I'm sure this is a little clumsy (the result of an amateur) but it has given me the result I want.

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;
}

With this I can call the function $list = getTitlesandIDs('John Doe') and then access both the title and id in the associative array for each instance. Like so:

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

Maybe that will help somebody some day -- let me know if you have any advice on making this more elegant.


$listofTitlesandIDs[$id] = $title;

You should loop over the array then using the foreach loop.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜