我的阵列没有给出正确的结果

时间:2009-10-25 17:05:08

标签: php

好吧,我不妨开始一个新的主题。这不像我希望的那样有效。这是从数据库构建的数组。请注意sidebar[0]sidebar[1]如何设置值“Favs”。这将在我不希望的表单上重复相同的值。所有重复的名称应该组合在一起。这可能吗?


Array
(
    [1] => Array
        (
            [date] => Sun, 25 Oct 2009
            [sidebar] => Array
                (
                    [0] => Array
                        (
                            [header] => Favs
                            [link] => google.com
                        )

                    [1] => Array
                        (
                            [header] => Favs
                            [link] => yahoo.com
                        )

                    [2] => Array
                        (
                            [header] => Offsite
                            [link] => dfdaf
                        )

                    [3] => Array
                        (
                            [header] => Something
                            [link] => something else
                        )
                )
        )
)

这是我需要的一个例子。

数据库很可能有多个具有相同侧边栏名称的行,如“Favs”或其他任何东西。这些标题应分为单个类别,并将所有链接分组。

Favs  google  http://...
Favs  yahoo   http://...
Favs  SO      http://...
bla   bla     http://...
bla   bla1    http://...

Should give:
Favs
  google
  yahoo
  SO
bla
  bla
  bla1

2 个答案:

答案 0 :(得分:0)

$conv = array();
foreach($nav['sidebar'] as $index => $data)
    foreach($data as $name => $entries)
        foreach($entries as $entry)
            $conv[$name][] = $entry;
$nav['sidebar'] = $conv;

答案 1 :(得分:0)

基于您的上一个数组结构:

<?php
$_list = array();
foreach($data as $k => $v){ // $data is get from $array['sidebar'];
    $_list[$v['header']][$v['link']] = "";
}
foreach($_list as $k => $v){
    echo "<ul>".$k;
    foreach($v as $kk => $vv){
        echo "<li><a href='".$vv."'>".$kk."</a></li>";
    }
    echo "</ul>";
}
?>

上面代码的数组结构:

Array
(
    [0] => Array
        (
            [header] => Favs
            [link] => google
            [url] => http://
        )

    [1] => Array
        (
            [header] => Favs
            [link] => yahoo
            [url] => http://
        )

    [2] => Array
        (
            [header] => Favs
            [link] => gmail
            [url] => http://
        )

    [3] => Array
        (
            [header] => Site
            [link] => facebook
            [url] => http://
        )

    [4] => Array
        (
            [header] => Site
            [link] => ymail
            [url] => http://
        )

    [5] => Array
        (
            [header] => Site
            [link] => myspace
            [url] => http://
        )

)