2011-07-30 42 views
1

這將是我第一次構建一個關聯數組。如果有人能幫助我,我會很感激。構建一個關聯數組

基本上,我想遍歷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]

就是這樣。我很感激您有時間提供的任何幫助。

+0

請澄清:調用數組應該返回什麼?標識,標題或作者或全部? –

+0

如果寫道:'$ listofTitlesandIDs [] = array(「title」=> $ title,「id」=> $ id)'; – Jeff

+0

然後,您無法在常量時間內查找ID和標題。 –

回答

0
$listofTitlesandIDs[$id] = $title; 

你應該遍歷數組,然後使用foreach循環。

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'),然後爲每個實例關聯數組中訪問標題和編號。像這樣:

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

也許這將有助於某人某一天 - 讓我知道如果你有任何建議,使這更優雅。