How to echo two items per one time by using PHP Foreach?

前端 未结 2 927
孤街浪徒
孤街浪徒 2021-01-14 23:06

I\'m using PHP to echo my products from DB. If we just use foreach will get the result one item per a loop but, Actually I want it echo two items per one times as below func

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-14 23:48

    You can use the modulus operator to make the check. If your iterator is a multiple of two it will output the appropriate elements (it does this by checking that the remainder is zero):

    public function last_upated_products() {
    
        $data = $this->newest_products_from_db('products');
        $out = '';
        if ($data) {
    
            $i = 0; 
    
            foreach ($data as $k => $row) {
    
                if( ($i % 2) === 0) {
                    $out .= '
    '; } $out .= '
    '; $out .= '
    '; $out .= 'img'; $out .= '
    ' . $row['prod_id'] . '% OFF
    '; $out .= '
    '; $out .= '
    $' . $row['prod_price'] . '

    ' . $row['prod_name'] . '

    '; $out .= '

    ' . $row['prod_descrip'] . '

    '; $out .= '
    '; $out .= '
    '; if( ($i + 1) % 2 === 0 || ($i + 1) === count($data) ) { $out .= '
    '; } $i++; } } return $out; }

    Note that the last bit ($i + 1) === count($data) is important in the event that your set holds an uneven number.

提交回复
热议问题