1

这是我的variables

<?php
    $submenu = array( array("submenu1", "submenu2", "submenu3", "submenu4"),
           array("submenuA", "submenuB", "submenuC", "submenuD"),
           array("submenuI", "submenuII", "submenuIII", "submenuIV")
    );

    $mainmenu="Main1, Main2, Main3";
?>

期望的output应该是:

Main1
 submenu1
 submenu2
 submenu3
 submenu4

Main2
 submenuA
 submenuB
 submenuC
 submenuD

Main3
 submenuI
 submenuII
 submenuIII
 submenuIV

谢谢!

4

4 回答 4

1

尝试这个:

<?php
    $submenu = array( array("submenu1", "submenu2", "submenu3", "submenu4"),
        array("submenuA", "submenuB", "submenuC", "submenuD"),
        array("submenuI", "submenuII", "submenuIII", "submenuIV")
    );
    $mainmenu="Main1, Main2, Main3";
    $mainArr=explode(',',$mainmenu);
    $newArr=array_combine($mainArr,$submenu);
    print_r($newArr);   
?>

您可以在http://writecodeonline.com/php/上对其进行测试

输出:

Array ( [Main1] => Array ( [0] => submenu1 [1] => submenu2 [2] => submenu3 [3] => submenu4 ) 
[ Main2] => Array ( [0] => submenuA [1] => submenuB [2] => submenuC [3] => submenuD ) 
[ Main3] => Array ( [0] => submenuI [1] => submenuII [2] => submenuIII [3] => submenuIV ) )
于 2013-03-15T04:34:32.630 回答
0

尝试这个:

<?php
    $submenu = array( array("submenu1", "submenu2", "submenu3", "submenu4"),
           array("submenuA", "submenuB", "submenuC", "submenuD"),
           array("submenuI", "submenuII", "submenuIII", "submenuIV")
         );

    $mainmenu="Main1, Main2, Main3";
    $mainmenu=explode(", ",$mainmenu);
    $tree=array_combine($mainmenu,$submenu);
    echo '<pre>';
    foreach($tree as $menuname=>$childArray)
    {
        echo "$menuname\n";
        foreach($childArray as $submenuname)
        {
            echo " $submenuname\n";
        }
    }
    echo '</pre>';
?>

输出:

<pre>Main1
 submenu1
 submenu2
 submenu3
 submenu4
Main2
 submenuA
 submenuB
 submenuC
 submenuD
Main3
 submenuI
 submenuII
 submenuIII
 submenuIV
</pre>
于 2013-03-15T04:49:12.533 回答
0

您可以尝试以下方法:

// Make your main menu an array
$mainMenuArray = preg_split("/, /", $mainmenu);

// Loop on the main menu
for($i = 0 ; $i < count($mainMenuArray) ; $i++)
{
    // print main menu entry
    echo $mainMenyArray[$i];

    // Print all sub menu linked to the current main menu entry
    foreach($submenu[$i] as $subMenuEntry)
        echo $subMenuEntry;

    echo "\n";
}
于 2013-03-15T04:35:17.603 回答
0
$submenu = array( array("submenu1", "submenu2", "submenu3", "submenu4"),
       array("submenuA", "submenuB", "submenuC", "submenuD"),
       array("submenuI", "submenuII", "submenuIII", "submenuIV")
     );

$mainmenu="Main1, Main2, Main3";

$main = explode(',', $mainmenu);

for($i=0; $i<count($main); $i++){
    for($j=0; $j<count($submenu); $j++){
        $array[$main[$i]][$j] = $submenu[$i][$j];
    }
}

$array现在包含您需要的内容。

于 2013-03-15T04:43:04.137 回答