我从数据库查出了一组数据
name     value
aaa      1111
aaa      2222
ccc      3333
aaa      4444
aaa      5555
bbb      6666
我要把这组数据通过PHP做成XML
重复的name 放在一个节点中
请问各位怎么做呢?
结果的样子为
<Attribute name="aaa" value="1111,2222,4444,5555"/>
<Attribute name="bbb" value="6666"/>
<Attribute name="ccc" value="3333"/>

解决方案 »

  1.   


    /*
    name value
    aaa 1111
    aaa 2222
    ccc 3333
    aaa 4444
    aaa 5555
    bbb 6666
    我要把这组数据通过PHP做成XML
    重复的name 放在一个节点中
    请问各位怎么做呢?
    结果的样子为
    <Attribute name="aaa" value="1111,2222,4444,5555"/>
    <Attribute name="bbb" value="6666"/>
    <Attribute name="ccc" value="3333"/>
    */
    $arr = array(
    array('name' => 'aaa', 'value' => '1111'),
    array('name' => 'aaa', 'value' => '2222'),
    array('name' => 'ccc', 'value' => '3333'),
    array('name' => 'aaa', 'value' => '4444'),
    array('name' => 'aaa', 'value' => '5555'),
    array('name' => 'bbb', 'value' => '6666')
    );$doc = new DOMDocument();
    $doc->formatOutput = true;
    $parent = $doc->createElement('parent');
    $array = array();
    foreach($arr as $val){
    $array[$val['name']][] = $val['value'];
    }foreach($array as $key => $val){
    $root = $doc->createElement('Attribute');
    $root->setAttribute('name', $key);
    $root->setAttribute('value', implode(',', $val));
    $parent->appendChild($root);
    }
    $doc->appendChild($parent);echo $doc->save('a.xml');//努力吧,慢慢会好的