PHP分组数组

时间:2016-01-24 23:04:43

标签: php xml xml-parsing

我知道这是有问题的,我试图按照我在其他帖子上找到的内容,但由于某种原因,我无法让它工作。我正在解析包含电视节目的多个xml文件。我试图按时间对所有节目进行分组。这就是我所拥有的。

  foreach ($items as $load){
   $contents[]= simplexml_load_file($load['guide']); //LOAD XML EACH CHANNEL INTO ARRAY
   }
  echo "COUNT OF CONTENT. . . ".count($contents)."<br>";  //SHOULD BE 36 TIME SLOTS
  foreach($contents as $content){ //BUILD MAIN ARRAYs
            $start[]=$content->programme['start'];
            $title[]=$content->programme->title;
            $desc[]=$content->programme->desc;
    }   
            $i=0;
            foreach($start as $a=>$b){ 
                    if($b==$start[$i]){
                                    $garray=array(
                                    'start'=> $start[$i],
                                    'title'=> $title[$i],
                                    'desc'=> $desc[$i],
                                    );
                                    $i++;

                                }else{
                                $i++;
                        }                   

                }   

我预计$ content中共有36个值。我将遍历每个$ contents,为start,title和desc创建一个数组。然后我想循环通过每个$ start将所有$ title和$ desc分组到相应的$ start下。出于某种原因,我不能用我所拥有的东西来完成这项工作。如果我如图所示运行它并检查我有3个$ garray的数量。我知道我遇到的第一个$ start应该在一个$ start下有18个标题。我希望以基于开头的以下格式获得它,每个阵列将有一个开始,但是多个标题和descs。我期望将最终的$ garray保存到其他程序可以访问的数组文件中。如果需要,它可以保存到xml。非常感谢任何帮助。

  array1(
      0=> 'start', 'title 1', 'desc 1',
      1=> 'start','title 2', 'desc 2',
      2=> 'start', 'title 3', 'desc 3',
      );

以下是xml的示例。每个文件都包含这样的信息,每个xml中可能有多个条目。我只对开始,标题和desc感兴趣。我可以解析每个,但无法按照相同的start值进行分组。

<programme start="20160122140000 -0500" stop="20160122150000 -0500"                  channel="I396.20453.schedulesdirect.org">

    <title lang="en">FABLife</title>

    <sub-title lang="en">Mark Cuban's Top 5 Secrets to Making Millions; Top 5 Must-Haves for 2016; Can Your Memorabilia Make You Rich?; Playroom Decorating on a Dime</sub-title>

    <desc lang="en">Mark Cuban (``Shark Tank''); top five must-haves; collectors try to guess the prices of celebrity memorabilia; creating a high-end playroom and eliminating toy clutter without breaking the bank.</desc>

    <credits>

        <guest>Mark Cuban</guest>

        <presenter>Tyra Banks</presenter>

        <presenter>Chrissy Teigen</presenter>

        <presenter>Joe Zee</presenter>

        <presenter>Lauren Makk</presenter>

        <presenter>Leah Ashley</presenter>

    </credits>

    <date>20160111</date>

    <category lang="en">Cooking</category>

    <category lang="en">Fashion</category>

    <category lang="en">House/garden</category>

    <category lang="en">How-to</category>

    <category lang="en">Series</category>

    <category lang="en">Talk</category>

    <episode-num system="onscreen">1074</episode-num>

    <episode-num system="dd_progid">EP02234030.0074</episode-num>

    <video>

        <aspect>16:9</aspect>

        <quality>HDTV</quality>

    </video>

    <audio>

        <stereo>stereo</stereo>

    </audio>

    <previously-shown start="20160111000000" />

    <subtitles type="teletext" />

    <rating system="VCHIP">

        <value>TV-PG</value>

    </rating>

</programme>

1 个答案:

答案 0 :(得分:0)

在XSLT 1.0中,您可以使用document()函数(即所有36个电视xml)组合多个XML文件,然后在称为Muenchian Method的过程中对大xml进行分组,该过程使用分组键,这里是@start属性。但是,上面两个任务需要两个转换(当然xslt大师可以在一个中完成!)。请注意您的帖子,您没有显示根xml标记来包装<programme>个节点。下面添加了通用<root>

XSLT (另存为.xsl或.xslt文件) - 首次转化

<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output version="1.0" encoding="UTF-8" indent="yes" />
<xsl:strip-space elements="*"/>

  <xsl:template match="root">
    <xsl:copy>
      <xsl:copy-of select="document('TV1.xml')/root/*"/>
      <xsl:copy-of select="document('TV2.xml')/root/*"/>
      <xsl:copy-of select="document('TV3.xml')/root/*"/>
      ...
      <xsl:copy-of select="document('TV36.xml')/root/*"/>
    </xsl:copy>
  </xsl:template>  

</xsl:transform>

如果你碰巧有一些开放式的XML,你可以动态地创建XSLT作为PHP字符串(通过PHP循环添加上面的xsl:copy-of行)并用loadXML()解析它在{PHP}中使用的load()

XSLT (另存为.xsl或.xslt文件) - 第二次转化

<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output version="1.0" encoding="UTF-8" indent="yes" />
<xsl:strip-space elements="*"/>

<xsl:key name="startkey" match="programme" use="@start" />

  <xsl:template match="root">
    <xsl:copy>
      <xsl:for-each select="programme[generate-id()= generate-id(key('startkey',@start)[1])]">
        <start>
          <xsl:attribute name="value"><xsl:value-of select="@start"/></xsl:attribute>   
          <xsl:for-each select="key('startkey', @start)">
            <xsl:copy>
              <title><xsl:value-of select="title"/></title>
              <description><xsl:value-of select="desc"/></description>
            </xsl:copy>
          </xsl:for-each>
        </start>
      </xsl:for-each>
    </xsl:copy>
  </xsl:template>    

</xsl:transform>

PHP 脚本(加载和处理两对XML和XSLT文件)

/******* FIRST TRANSFORMATION *******/
$doc1 = new DOMDocument();
$doc1->load('TV1.xml');

$xsl1 = new DOMDocument;
$xsl1->load('FirstXSLTScript.xsl');

// Configure the transformer
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl1); 

// Transform XML source
$combineXml = $proc->transformToXML($doc1);

/******* SECOND TRANSFORMATION *******/
$doc2 = new DOMDocument();
$doc2->loadXML($combineXml);

$xsl2 = new DOMDocument;
$xsl2->load('SecondXSLTScript.xsl');

// Configure the transformer
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl2); 

// Transform XML source
$finalXml = $proc->transformToXML($doc2);

// Save output to file
$xmlfile = 'FinalOutput.xml';
file_put_contents($xmlfile, $finalXml);

最终输出 (添加其他示例数据以进行演示)

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <start value="20160122140000 -0500">
    <programme>
      <title>FABLife</title>
      <description>Mark Cuban (``Shark Tank''); top five must-haves; collectors try to guess the prices of celebrity memorabilia; creating a high-end playroom and eliminating toy clutter without breaking the bank.</description>
    </programme>
    <programme>
      <title>Blacklist</title>
      <description>Elizabeth 'Liz' Keen, a new FBI profiler has her entire life uprooted when a mysterious criminal, Raymond Reddington, on the FBI's Top Ten Most Wanted List turns himself in and insists on speaking to her.</description>
    </programme>
    <programme>
      <title>Persons Of Interest</title>
      <description>An ex-assassin and a wealthy programmer save lives via a surveillance AI that sends them the identities of civilians involved in impending crimes. However, the details of the crimes--including the civilians' roles--are left a mystery.</description>
    </programme>
  </start>
  <start value="20160142140000 -0500">
    <programme>
      <title>Sense8</title>
      <description>A group of people around the world are suddenly linked mentally, and must find a way to survive being hunted by those who see them as a threat to the world's order.</description>
    </programme>
    <programme>
      <title>Scandal</title>
      <description>A former White House Communications Director starts her own crisis management firm only to realize her clients are not the only ones with secrets.</description>
    </programme>
  </start>
  <start value="20160152140000 -0500">
    <programme>
      <title>Graceland</title>
      <description>A rookie FBI agent is sent to a house for undercover agents in Southern California, where he is trained by a former legend FBI agent.</description>
    </programme>
  </start>
</root>