Stuart Brian Stuart Brian - 10 days ago 5
PHP Question

How to number items in for-loop php

I have this code that select content from database and loop all, and few items are specify to be different by adding method (type-A and type-B) in database, so now i want to give all type-B numbers like 1,2,3 depending on number of type in database.
I could have do this using the id in database but it not number accordingly so i need just assign new number to list how many of it i have.

<?php
$getReply = $reply_stmt->getAll(); // this from my database
if(!is_null($getReply)){
foreach($getReply as $row){
$name = $row->itemname;
$method = $row->method;
}
if($method == 'type-B'){
$number = 1;
$number++;
echo $number."B-class<br/>".$name."".$method;
}else{
echo $name."".$method;
}
}
?>


Now i want to return something like this


1 B-class

Peter type-B

John type-A

2 B-class

Mike type-B

Answer

I am not sure but try to something like this...

$getReply = $reply_stmt->getAll(); // this from my database
    if(!is_null($getReply)){
        $number = 1;
        foreach($getReply as $row){
         $name = $row->itemname;
         $method = $row->method;
            if($method == 'type-B'){
               echo  $number." B-class<br/>".$name." ".$method;
               $number++;
            }else{
              echo  $name." ".$method;
            }
        }

    }