0

Here is the array

    $array = [
a=>["name"= "name1", "id"="1"..], 
b=>["name"= "name2", "id"="2"..], 
c=>["name"= "name3", "id"="3"..],
d=>["name"= "name4", "id"="4"..],
e=>["name"= "name5", "id"="5"..], 
f=>["name"= "name6", "id"="6"..],......);

What i want to achieve is foreach loop to echo items like this

Design

Image Link

here is what i did, but no luck

$len = count($moduleTypes); 
$firsthalf = array_slice($moduleTypes, 0, $len / 2);
$secondhalf = array_slice($moduleTypes, $len / 2);

Break array and echo each one individually, Foreach loop has to continue, but on second iteration, it need to loop two times [B,C] and next iteration one time [D], and so on.. check image for perspective

3
  • You say you want to echo items like this, what sort of data is it, how are you displaying it? Your array definition gives no clue and your attempt also is no help in trying to understand the context of your question. Commented Dec 29, 2018 at 7:37
  • yes, i've updated array example Commented Dec 29, 2018 at 7:48
  • @AdhikJoshi what HTML you have applied to show data like this (what you posted in picture).Add that HTML TOO Commented Dec 29, 2018 at 8:03

5 Answers 5

2

I think that's what you need to

for ($i = 1; $i <= count($array); $i = $i + 3) {

echo '<br>';
echo '-' . $array[$i-1] . '-';
if (!isset($array[$i])) break;
echo '<br>';
echo $array[$i] . ' ';
if (!isset($array[$i+1])) break;
echo $array[$i+1];

}

You can play here http://sandbox.onlinephpfunctions.com/code/b3fba97df75b235b1acccacf82b800e21f3924f5

Sign up to request clarification or add additional context in comments.

Comments

1

Tricky part is the HTML table. Congrats on successfully nerd sniping me.

<?php

$arr = ['A','B','C','D','E','F','G','H','I','J','K','L'];

$second_row = [];
$first_row_next = 1;

echo "<table border='1'>";
echo "<tr>";

for($i=0;$i<count($arr);$i++){
  if($i%3 == 0){
    echo "<td rowspan='2'>$arr[$i]</td>"; // belongs to the first row with rowspan
  }else if($i == $first_row_next){
    echo "<td>$arr[$i]</td>";// belongs to first row with no rowspan since it's other subordinate will come down under it.
    $first_row_next += 3;
  }else{
    $second_row[] = $arr[$i];
  }
}

echo "</tr>";
echo "<tr><td>".implode("</td><td>",$second_row)."</td></tr>";
echo "</table>";

Output:

It generates the following HTML table:

<table border='1'>
  <tr>
    <td rowspan='2'>A</td>
    <td>B</td>
    <td rowspan='2'>D</td>
    <td>E</td>
    <td rowspan='2'>G</td>
    <td>H</td>
    <td rowspan='2'>J</td>
    <td>K</td>
  </tr>
  <tr>
    <td>C</td>
    <td>F</td>
    <td>I</td>
    <td>L</td>
  </tr>
</table>

Algorithm:

  • We see this table as 2 rows.
  • So, first row would have A,B,D,E,G,H,J,K.
  • Second row has C,F,I,L.
  • If you look at the array indexes, every value at indexes 0,3,6,9.... make it to have a rowspan of 2 in the table. Hence the first condition: if($i%3 == 0).
  • For values of the first row, which have other subordinates below them, their indexes follow as 1,4,7,10... etc with no rowspan. $first_row_next keeps track of it and outputs the td data accordingly.
  • For the second row, any array index that does not meet the above requirements, falls under second row. Hence, we collect them in the second array and output the second row in the end.

Working of HTML table:

The first row is:

<tr>
    <td rowspan='2'>A</td>
    <td>B</td>
    <td rowspan='2'>D</td>
    <td>E</td>
    <td rowspan='2'>G</td>
    <td>H</td>
    <td rowspan='2'>J</td>
    <td>K</td>
</tr>

This generates the first row. So far so good. The second row is:

<tr>
    <td>C</td>
    <td>F</td>
    <td>I</td>
    <td>L</td>
</tr>

The way this gets rendered is:

  • There are total 2 rows in the table.
  • When C is to be rendered, it looks for space in A but doesn't get it, so it moves to the next column. It gets in B, so gets attached.
  • For F, it finds a space for a td to be added below E and so on with the other values.

Comments

1

This is not the exact solution but it will exact logic that you can implement in your html code

<?php

$array = array(1,2,3,4,5,6,7);

$counter = 1;
$temp = "";
foreach($array as $val){

    if($temp == 1){
        echo "E$val<br>";
        $temp=0;
        $counter++;
    }else{
        if($counter % 2 == 0){
            echo "E$val<br>";

            $temp = 1;
        }else{
            echo "O$val<br>";
        }
    }

    $counter++;

}

O/p Look likes

O1
E2
E3
O4
E5
E6
O7

Where O is A,D,G And E is B,C,E,F

Update

foreach($array as $key => $val){

    if($temp == 1){
        echo "E".$val['name']."<br>";
        $temp=0;
        $counter++;
    }else{
        if($counter % 2 == 0){
            echo "E".$val['name']."<br>";

            $temp = 1;
        }else{
            echo "O".$val['name']."<br>";
        }
    }
    $counter++;
}

Comments

0
<?php
$array = [
"a"=>["name"=> "name1", "id"=>"1"], 
"b"=>["name"=> "name2", "id"=>"2"], 
"c"=>["name"=> "name3", "id"=>"3"],
"d"=>["name"=> "name4", "id"=>"4"],
"e"=>["name"=> "name5", "id"=>"5"],
"f"=>["name"=> "name6", "id"=>"6"]
];

$keys = array_keys($array);

foreach(array_keys($array) as $i => $key) {
    switch($i % 3) {
        case 2: // case: 3rd values
            continue;
        break;
        case 1: // case: 2nd values
            $nextkey = $keys[$i + 1];
            // show $key and $nextkey
            print_r($array[$key]);
            if( $array[$nextkey] ) {
                print_r($array[$nextkey]);
            }
            echo "---\r\n"; // delimiter
        break;
        default:
            // case: very first and every 4th values
            print_r($array[$key]);
            echo "---\r\n"; // delimiter
    }

}

You can make use of array_keys and then use the index-value as if you would use a for-loop. I do not know why you want to use a foreach-loop. For-loop seems to be better for this. switch-case can make it more readable, you can comment your cases.

Comments

0

I can appreciate @nice_dev's use of HTML and rowspan to satisfy the required design layout. I'd like to recommend an alternative snippet to produce the same markup.

My snippet uses a multidimensional array to build/retain the two rows of table cells. Then the array is looped to present the table rows.

Code: (Demo)

$array = range('A', 'L');

$tdsByRow = [];
foreach ($array as $i => $v) {
    switch ($i % 3) {
        case 0:
            $tdsByRow[0][] = '<td rowspan="2">' . $v . '</td>';
            break;
        case 1:
            $tdsByRow[0][] = '<td>' . $v . '</td>';
            break;
        case 2:
            $tdsByRow[1][] = '<td>' . $v . '</td>';
            break;
     }
}

if ($tdsByRow) {
    echo '<table border="1">';
        foreach ($tdsByRow as $tds) {
            echo "<tr>" . implode($tds) . "</tr>";
        }
    echo "</table>";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.