-1

can u please help me on this. I have an array with 6 items, I want to print 2 items per line separated by commas, I have this code:

$rates[] = array("2020-01-01"=>3000);
$rates[] = array("2020-01-02"=>3010);
$rates[] = array("2020-01-03"=>3020);
$rates[] = array("2020-01-04"=>3021);
$rates[] = array("2020-01-05"=>3030);
$rates[] = array("2020-01-06"=>3035);

$rates_count = count($rates);
$total = $rates_count;
$col = 2;

for ($i = 0; $i < $total; $i++) {

    $date = key($rates[$i]);
    $value = end($rates[$i]);

    if ($i % $col != 0) {
            echo "{$date},";
            echo "{$value},";        
    } else {
        echo "{$date},";
        echo "{$value}";
        echo "</br>";
    }
}

This code print this:

2020-01-01,3000
2020-01-02,3010,2020-01-03,3020
2020-01-04,3021,2020-01-05,3030
2020-01-06,3035,

I want this:

2020-01-01,3000,2020-01-02,3010
2020-01-03,3020,2020-01-04,3021
2020-01-05,3030,2020-01-06,3035

Where is the error? Thanks for any help.

Takeov3r
  • 25
  • 1
  • 4

1 Answers1

0

I tested this and your output should be correct now

if ($i % $col == 0) {
        echo "{$date},";
        echo "{$value},";        
} else {
    echo "{$date},";
    echo "{$value}";
    echo "</br>";
}

Output:

2020-01-01,3000,2020-01-02,3010
2020-01-03,3020,2020-01-04,3021
2020-01-05,3030,2020-01-06,3035 

I changed the comparison to be " == 0"

The first value in the iteration will be cero because 0 % 2 = 0

0 % 2 = 0
1 % 2 = 1
2 % 2 = 0
3 % 2 = 1
4 % 2 = 0
5 % 2 = 1
... and so on

The condition was returing false in the first iteration, it was fixed by changing the comparison of the remainder to be equal to cero.

Manuvo
  • 748
  • 5
  • 15