Question

I have an array like so:

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
  )
)

and I am trying to write a foreach to have each of those array in the table row and the values in table data

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

Any help would be appreciated.

Was it helpful?

Solution

A possible approach would be using a foreach loop with the key/value clause:

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

OTHER TIPS

If I understand what you want to do, use implode:

foreach ($data as $value) {
    echo '<tr><td>'.implode('</td><td>', $value).'</td></tr>' ;
}
    <?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>";
    }   
}
?>

should work for your "weired" array (which is just nested by the way)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top