0

我已经完成了我的研究。但是两天后我要疯了。我真的想避免向 MYSQL 发送多个查询。我知道解决方案是迭代并在新数组中插入值。但老实说,我不知道从哪里开始。我想创建的这个多维数组超出了我的范围。谢谢!

我需要打开以下MYSQL Result:

    categories  subcategories   items
    ----------  -------------   ------
    ART       painter        picasso
    ART       painter        VanGogh
    ART       sculpture      Rodin
    ART       sculpture      Serra
    MUSIC     Rock           Lennon
    MUSIC     Rock           Mercury
    MUSIC     Classic        Mozart
    THEATRE   Drama          Shakespeare
    THEATRE   Drama          Moliere

进入这个 PHP 数组:

 $Data = array (
    name=>'ARTISTS', 
    children=>array(
        array('name'=>'ART', 
                children=>array(
        array('name'=>'Painting', children=>array(array('name'=>'picasso'),array('name'=>'Van Gogh'))),
        array('name'=>'Sculpture', children=>array(array('name'=>'Rodin'),array('name'=>'Serra')))
        )),
        array('name'=>'MUSIC', 
                children=>array(
        array('name'=>'Rock', children=>array(array('name'=>'Lennon'),array('name'=>'Mercury'))),
        array('name'=>'Classic', children=>array(array('name'=>'Mozart')))
        )),
        array('name'=>'THEATRE', 
                children=>array(
        array('name'=>'Drama', children=>array(array('name'=>'Shakespeare'),array('name'=>'Moliere')))
        ))
    )
);   

我唯一知道的是,这个 PHP 数组(手动编写)一旦通过 json_encode 传递它就会生成一个完美的 JSON。所以最后一部分不是问题。我只是把它放在这里解释这一切的去向。

$json = json_encode($Data);

生成:

{"name":"ARTISTS","children":[{"name":"ART","children":[{"name":"Painting","children":[{"name":"picasso"},{"name":"Van Gogh"}]},{"name":"Sculpture","children":[{"name":"Rodin"},{"name":"Serra"}]}]},{"name":"MUSIC","children":[{"name":"Rock","children":[{"name":"Lennon"},{"name":"Mercury"}]},{"name":"Classic","children":[{"name":"Mozart"}]}]},{"name":"THEATRE","children":[{"name":"Drama","children":[{"name":"Shakespeare"},{"name":"Moliere"}]}]}]}
4

2 回答 2

1

我会放弃应用所有那些不必要的name标签children的想法。当您获得数据库结果集时,只需对其进行迭代并直接设置所有数组索引项。

$data = array();
while ($row = /*  your DB row fetch here */) {
    $data[$row['categories']][$row['subcategories']][] = $row[$items];
}

$json_data = json_encode($data);
于 2013-05-07T20:01:12.830 回答
0

如前所述Mike Brant,您应该使用类别名称作为索引。但是,如果您仍然需要一个能够给出您给出的结果的解决方案,这里有一些代码:

$formatted = array() ;

foreach($data as $part){
    if (!array_key_exists($part['categories'], $formatted)){
        $formatted[$part['categories']] = array(
            "name" => $part['categories'],
            "children" => array()
        );
    }

    $sub = &$formatted[$part['categories']]['children'] ;

    if (!array_key_exists($part['subcategories'], $sub)){
        $sub["name"] = $part['subcategories'] ;
        $sub["children"] = array() ;
    }

    $items = &$sub['children'] ;

    $items[$part['items']] = array("name"=>$part['items']) ;
}

print_r($formatted);
于 2013-05-07T20:11:06.410 回答