打印2D阵列

时间:2015-06-29 16:47:05

标签: javascript php arrays codeigniter

我正在尝试打印子元素。关注this example。怎么做?。

$myarray = array("DO"=>array('IDEAS','BRANDS','CREATIVE','CAMPAIGNS'),
"JOCKEY"=>array('IDEAS','BRANDS','CREATIVE','CAMPAIGNS'),
"CREATE"=>array('IDEAS','BRANDS','CREATIVE','CAMPAIGNS'),
"INNOVATE"=>array('IDEAS','BRANDS','CREATIVE','CAMPAIGNS')); 

foreach($myarray as $key => $element){
    echo "<span class='rotate'>$element</span>";
    foreach($element as $subkey => $subelement){
        $out .= "$subelement";
        echo "<span class='rotate'>$out</span>";
    }
}

3 个答案:

答案 0 :(得分:1)

您需要执行以下操作: -

<?php
$myarray = array("DO"=>array('IDEAS','BRANDS','CREATIVE','CAMPAIGNS'),
"JOCKEY"=>array('IDEAS','BRANDS','CREATIVE','CAMPAIGNS'),
"CREATE"=>array('IDEAS','BRANDS','CREATIVE','CAMPAIGNS'),
"INNOVATE"=>array('IDEAS','BRANDS','CREATIVE','CAMPAIGNS')); 
$out = ''; // define the out variable
foreach($myarray as $key => $element){
    echo "<span class='rotate'>$key</span>.<br><br>"; // print the indexes of main array
    foreach($element as $subkey => $subelement){
        $out .= "$subelement";
        echo "<span class='rotate'>$out</span><br>"; // print the sub elements present in the form of array at each indexes of the main array 
    }
}
?>

输出: - http://prntscr.com/7mribs

答案 1 :(得分:0)

<?php<br/>
$cars = array<br/>
   (<br/>
   array("Volvo",22,18),<br/>
   array("BMW",15,13),<br/>
   array("Saab",5,2),<br/>
   array("Land Rover",17,15)<br/>
   );<br/>

for ($row = 0; $row <  4; $row++) {<br/>
   echo "<p><b>Row number $row</b></p>";<br/>
   echo "<ul>";<br/>
   for ($col = 0; $col <  3; $col++) {<br/>
     echo "<li>".$cars[$row][$col]."</li>";<br/>
   }<br/>
   echo "</ul>";<br/>
}<br/>
?>

答案 2 :(得分:0)

您提供的链接无效。从你的帖子来看,我看起来你想要打印索引及其下面的子项,所以这个片段就是这样:

<?php
$myarray = array("DO"=>array('IDEAS','BRANDS','CREATIVE','CAMPAIGNS'),
"JOCKEY"=>array('IDEAS','BRANDS','CREATIVE','CAMPAIGNS'),
"CREATE"=>array('IDEAS','BRANDS','CREATIVE','CAMPAIGNS'),
"INNOVATE"=>array('IDEAS','BRANDS','CREATIVE','CAMPAIGNS')); 

foreach($myarray as $index => $s)
{
    echo "<ul>";
    echo "<li>" . $index . "<ul>";

    foreach($s as $sub)
    {
        echo "<li>" . $sub . "</li>";
    }

    echo "</ul></li></ul>";

}
?>