foreach为嵌套数组

时间:2014-05-07 13:23:50

标签: php arrays foreach

我有一个像这样的数组:

Array(
  [0] => Array(
    [0] => 1
    [1] => test
    [2] => 2014-05-06
    [3] => Blah, Blah, Blah
    [4] => admin-uploads/test.jpg
  )
  [1] => Array(
    [0] => 9
    [1] => Test 3
    [2] => 2014-05-07
    [3] => This is the second Test.vcxvjmckxlmvcx
    [4] => admin-uploads/
  )
  [2] => Array(
    [0] => 10
    [1] => Test 3
    [2] => 2014-05-07
    [3] => This is the second Test.
    [4] => admin-uploads/test2.jpg
  )
)

我正在尝试写一个foreach以使表格行中的每个数组和表格数据中的值

foreach($data as $key=>$value){
  echo '<tr>';
    echo '<td>' . $value . '</td>';
  echo '</tr>';
}

任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:0)

一种可能的方法是使用带有键/值子句的foreach循环:

foreach($data as $key=>$value){
   echo '<tr>';
   foreach($value as $sub_value) {
      echo '<td>' . $sub_value . '</td>';
   }
   echo '</tr>';
}

答案 1 :(得分:0)

如果我理解你想做什么,请使用implode:

foreach ($data as $value) {
    echo '<tr><td>'.implode('</td><td>', $value).'</td></tr>' ;
}

答案 2 :(得分:0)

    <?php
echo "abc";
$data = array(  
                0 => array(0 => 1, 1 => "test", 2 => "2014-05-06", 3 => "Blah Blah Blah", 4 => "admin-uploads/test.jpg"), 
                1 => array(0 => 9, 1 => "Text 3", 2 => "2014-05-07", 3=>"This is the second test.vcxvjmckxlmvcx", 4 => "admin-uploads/"), 
                2 => array(0 => 10, 1 => "Text 3", 2 => "2014-05-07", 3=>"This is the second test.", 4 => "admin-uploads/test2.jpg")
            );

foreach($data as $item)
{
    foreach($item as $key => $value)
    {
        echo "Key: ".$key." <br> Value:".$value."<br><br>";
    }   
}
?>

应该适用于你的“weired”数组(它只是嵌套的方式)