2013-10-09 184 views
0

我試圖找到這個問題之前詢問,但不能真正弄清楚。二維陣列

我已經是一個循環,它實際上是一個循環與使用simplexml_load_file

現在這個XML文件中讀取XML數據有,我想讀的實際投入到一個數組..二維數組數據..

所以這個XML文件有一個名爲Tag的孩子,並且有一個叫做Amount的孩子。 數量總是不一樣,但標籤通常是相同的,但有時也會改變。

什麼我想現在要做的是:

例子:

這是XML例子:

<?xml version="1.0"?> 
<Data> 
<Items> 
    <Item Amount="9,21" Tag="tag1"/> 
    <Item Amount="4,21" Tag="tag1"/> 
    <Item Amount="6,21" Tag="tag2"/> 
    <Item Amount="1,21" Tag="tag1"/> 
    <Item Amount="6,21" Tag="tag2"/> 

</Data> 
</Items> 

現在我有一個循環讀取這個,看到的標記是並加總金額。 它與2個循環和兩個不同的數組一起工作,我想在單個循環中將它全部放在一個數組中。

我想是這樣的:

$tags = array(); 
     for($k = 0; $k < sizeof($tags); $k++) 
     { 
       if (strcmp($tags[$k], $child['Tag']) == 0) 
      { 
       $foundTAG = true; 
       break; 
      } 
      else 
       $foundTAG = false; 
     } 


     if (!$foundTAG) 
     { 
      $tags[] = $child['Tag']; 
     } 

,然後在代碼的某個地方我嘗試添加到陣列的不同變化($計數器的數額纔算數一起):

$tags[$child['Tag']][$k] = $counter; 
$tags[$child['Tag']][] = $counter; 
$tags[][] = $counter; 

我嘗試了幾個其他組合,我已經刪除,因爲它沒有工作..

好吧,這可能是一個真正的菜鳥問題,但我昨天開始用PHP,沒有ide一個是如何多維數組工作:)

謝謝

+0

那麼最終結果應該是一個包含標籤和它們各自總數的數組? –

+0

$ tags = array();對於($ k = 0; $ k Svetoslav

+1

您的XML格式錯誤,'items'應該在'data'之前關閉 –

回答

1

這是你可以通過簡單的XML返回的對象迭代:

$xml=simplexml_load_file("/home/chris/tmp/data.xml"); 
foreach($xml->Items->Item as $obj){ 
    foreach($obj->Attributes() as $key=>$val){ 
     // php will automatically cast each of these to a string for the echo 
     echo "$key = $val\n"; 
    } 
} 

因此,建立與總數爲每個標籤的數組:

$xml=simplexml_load_file("/home/chris/tmp/data.xml"); 
$tagarray=array(); 
// iterate over the xml object 
foreach($xml->Items->Item as $obj){ 
    // reset the attr vars. 
    $tag=""; 
    $amount=0; 
    // iterate over the attributes setting 
    // the correct vars as you go 
    foreach($obj->Attributes() as $key=>$val){ 
     if($key=="Tag"){ 
      // if you don't cast this to a 
      // string php (helpfully) gives you 
      // a psuedo simplexml_element object 
      $tag=(string)$val[0]; 
     } 
     if($key=="Amount"){ 
      // same as for the string above 
      // but cast to a float 
      $amount=(float)$val[0]; 
     } 
     // when we have both the tag and the amount 
     // we can store them in the array 
     if(strlen($tag) && $amount>0){ 
      $tagarray[$tag]+=$amount; 
     } 
    } 
} 
print_r($tagarray); 
print "\n"; 

如果圖案發生變化或者您決定穿藍色襪子(xml對色彩極其敏感),這將會非常可怕。正如你所看到的,處理xml問題的孩子是很乏味的 - 在委員會會議室中另一個設計決定:-)

+0

非常感謝你的幫助。我的代碼幾乎是一樣的,但它沒有工作,因爲我沒有做(字符串)在數組:)。我認爲PHP會知道它的一個字符串,如果你將字符傳遞給一個數組/ var :) – user1089366