views:

198

answers:

5

Hi I have an php array of ten numbers

$arr = array("first" => "1", "second" =>"2", "Third" =>"3", "Fourth" =>"4",
"fifth" =>"5",, "sixth" =>"6", "seventh" =>"7", "eighth" =>"8", 
"ninth" =>"9","tenth"="10");

I have to place these values in a <td> by spliting the array in numbers of three such that my td contains first td contains <td>the first three values of an aray</td>
second td contains <td>the next three values of an aray</td>
third td contains <td>the next three values of an aray</td>
if the remaining values in less than three in number it must be in the another td say now i have tenth value so my last td must contain tenth value

+1  A: 

Don't know of there is a function which will split the array like that.. Perhaps do it in a for ?

$cnt = count($arr);
for($point = 0; $point < $cnt; $point += 3)
{
    echo("<td>".$arr[$point]." ".$arr[$point+1]." ".$arr[$point + 2]."</td>");
}

EDIT: Of course, inside you should check if there are values left. This assumes the length of the array is a multiple of 3 (which, as you stated, might not be the case)

nc3b
+2  A: 

PHP's function array_splice was pretty much made for this job:

$arr = range(1,10);
while (count($arr)) {
  $three = array_splice($arr,0,3);
  echo "<td>";
  echo implode(" ",$three);
  echo "</td>";
}

Output:

<td>1 2 3</td><td>4 5 6</td><td>7 8 9</td><td>10</td>

array_splice($arr,0,3) removes the first 3 elements from $arr and returns them into $three

gnarf
+1  A: 

See this another example

<?php
$arr = array("first" => "1","second" => "2","Third" => "3","Fourth" => "4","fifth" => "5","sixth" => "6","seventh" => "7","eighth" => "8","ninth" => "9","tenth" => "10");
echo "<br>";
print_r($arr);
echo "<br>";

?>

<table cellpadding="0" cellspacing="0" border="1">
<tr>
<td>
<?php
$i=1;
foreach ($arr as $value) {
    echo $value." ";
    if($i%3==0) echo "</td><td>";
    $i++;
}
?>
</td>
</tr>
</table>
Karthik
+7  A: 

You may use array_chunk.

foreach(array_chunk($arr,3) as $row)
{
    echo "<td>"; 
    echo implode(" ",$row);
    echo "</td>"; 
}
SpawnCxy
+1  A: 

This will do the trick.

    <?php


$array = array("first" => "1", "second" =>"2", "Third" =>"3", "Fourth" =>"4",
"fifth" =>"5", "sixth" =>"6", "seventh" =>"7", "eighth" =>"8", 
"ninth" =>"9","tenth"=>"10");



array_to_td($array, 3);

//$number is the number of elements in a <td></td>.

function array_to_td($array, $number){

 $count = 0;

 foreach($array as $key => $value){
  if ($count == 0){
   print "<td>";  
  }

  $count++;

  print $value;

  if($count == $number ){
   print "</td>";
   $count = 0;
  }


  }
  if ($count != 0){
   print "</td>"; 
  }  

 }

You can do any other operations on the given array as it will remain unchanged.

Abraham
ya it will do but look at the answer from gnarf it is simplerBut thanks for your effort
udaya