2010-08-02 83 views
0

我試圖檢索使用SimpleXML從XML文件中的項目N多,把信息變成一個2維數組,如:檢索N條記錄從XML文件PHP

[0][name] 
[0][image] 
[1][name] 
[1][image] 
[2][name] 
[2][image] 

在這種情況下N個項目將6

我願意做這兩種方式,
1.搶第0-6鍵和值
2.或者從XML文件的隨機6。

該xml文檔有300條記錄。

XML Example: 

<xml version="1.0"> 
    <info> 
     <no>1</no> 
     <name>Name</name> 
     <picture>http://www.site.com/file.jpg</picture> 
     <link>http://www.site.com</link> 

    </info> 
</xml> 

這是我到目前爲止。讀取xml會產生一個二維數組:

function getItems($file_id, $item_count=null) 
{ 
    switch ($file_id) 
    { 
     case '2': 
     $file = "http://xml_file.xml"; 

     if ($xml = simplexml_load_file($file)) 
     { 
      foreach ($xml->info as $info) 
      { 
       $var[] = array(
        "Name" => (string)$info->name, 
        "Image" => (string)$info->picture);  
      } 
      return $var; 
     } 
    } 
} 

我可以使用for循環嗎?或者以某種方式使用計數變量?

+0

可以請你發佈一些XML與該代碼? – Gordon 2010-08-02 13:48:29

+0

第二代碼塊從頂部... – rrrfusco 2010-08-02 14:48:36

回答

1

編輯
我有困難,將一個for循環以及嵌套節點的foreach。


回答檢索N條記錄

function getItems($file_id, $item_count=null) 
{ 
    switch ($file_id) 
    { 
     case '2': 
     $file = "http://xml_file.xml"; 

     if ($xml = simplexml_load_file($file)) 
     { 
      $i=0; 
      foreach ($xml->info as $info) 
      { 
       if ($i < $item_count) 
       { 
        $var[] = array(
         "Name" => (string)$info->name, 
         "Image" => (string)$info->picture); 
       } 
       $i++; 
      } 
      return $var; 
     } 
    } 
} 

任何人都可以提出如何從300條記錄得到n個隨機記錄?


答案爲隨機記錄

function getItems($file_id, $item_count=null) 
{ 
    switch ($file_id) 
    { 
     case '2': 
     $file = "http://xml_file.xml"; 

     if ($file) 
     { 
      $xml = simplexml_load_file($file); 

      $k = array(); 
      for ($i=0; $i<$item_count; $i++) 
      { 
       $k[] = rand(1,300) 
      } 

      $i=0; 
      foreach ($xml->info as $info) 
      { 
       if ($i < $item_count) 
       { 
        if (in_array($i, $k)) 
        { 
         $var[] = array(
          "Name" => (string)$info->name, 
          "Image" => (string)$info->picture); 
        } 
       } 
       $i++; 
      } 
      return $var; 
     } 
    } 
} 
3

我可以使用for循環嗎?或以某種方式使用 計數變量?

for($i = 0; $i < count($xml->info); $i++) 
{ 
    // your code.... 
} 

更新:

使用這個,如果你想限制爲6:

for($i = 0; $i <= 6; $i++) 
{ 
    // your code.... 
} 
+0

我需要六個,您的代碼返回300個鍵。 – rrrfusco 2010-08-02 09:29:44

+0

@rrrfusco:然後添加自己的限制? (N代替'Count(...' – Wrikken 2010-08-02 09:32:58

+0

@rrrfusco:請參閱我的更新回答。 – Sarfraz 2010-08-02 09:36:21