从php loop&中找到独特的包裹新元素

时间:2013-12-04 13:59:16

标签: php sorting

我正在跟踪php循环中的数据

<ul id="alpha-list">
    <li data-alpha="A">Apple</li>
    <li data-alpha="B">Bat</li>
    <li data-alpha="B">Ball</li>
    <li data-alpha="A">Angel</li>
    <li data-alpha="D">Dog</li>
    <li data-alpha="C">Cat</li>
</ul>

我想找到独特的“data-alpha”属性&amp;将它们包装在父“ul li”中,这样​​每个“data-alpha”的结果应该与此类似。

<ul id="alpha-list">
    <li data-alphabet="A">
        <ul>
           <li data-alpha="A">Angel</li>
           <li data-alpha="A">Apple</li>
        </ul>
    </li>
    <li data-alphabet="B">
        <ul>
           <li data-alpha="B">Ball</li>
           <li data-alpha="B">Bat</li>
        </ul>
    </li>
    ..... 
</ul>

如何在php中实现这一点?任何指导将不胜感激。

2 个答案:

答案 0 :(得分:0)

我认为您需要创建双维数组然后循环数组

答案 1 :(得分:0)

$html = <<<EOL
<ul id="alpha-list">
    <li data-alpha="A">Apple</li>
    <li data-alpha="B">Bat</li>
    <li data-alpha="B">Ball</li>
    <li data-alpha="A">Angel</li>
    <li data-alpha="D">Dog</li>
    <li data-alpha="C">Cat</li>
</ul>
EOL;

$dom = new DOMDocument();
$dom->loadHTML($html);

$data = array();

foreach ($dom->getElementsByTagName('li') as $node) {
    $data[$node->getAttribute('data-alpha')][] = $node->textContent;
}

ksort($data);

$dom = new DOMDocument();

$ulElement = $dom->createElement('ul');
$ulElement->setAttribute('id', 'alpha-list');

foreach ($data as $char => $words) {
    $parentLiElement = $dom->createElement('li');
    $parentLiElement->setAttribute('data-alphabet', $char);

    $childUlElement = $dom->createElement('ul');

    foreach ($words as $word) {
        $childLiElement = $dom->createElement('li');
        $childLiElement->setAttribute('data-alpha', $char);
        $childLiElement->appendChild($dom->createTextNode($word));

        $childUlElement->appendChild($childLiElement);
    }

    $parentLiElement->appendChild($childUlElement);
    $ulElement->appendChild($parentLiElement);
}

$dom->appendChild($ulElement);

echo $dom->saveHTML();

这应该产生:

<ul id="alpha-list">
    <li data-alphabet="A">
        <ul>
            <li data-alpha="A">Apple</li>
            <li data-alpha="A">Angel</li>
        </ul>
    </li>
    <li data-alphabet="B">
        <ul>
            <li data-alpha="B">Bat</li>
            <li data-alpha="B">Ball</li>
        </ul>
    </li>
    <li data-alphabet="C">
        <ul>
            <li data-alpha="C">Cat</li>
        </ul>
    </li>
    <li data-alphabet="D">
        <ul>
            <li data-alpha="D">Dog</li>
        </ul>
    </li>
</ul>