HardyProject
HardyProject

Reputation: 9

How to get value numbering ($no++) in foreach?

I have 2 foreach with different query. The first foreach displays the customer name and transaction number.

Transaction number value in the first foreach is not from Database but from looping $no++.

How to get $no++ value from first foreach to store in second foreach based on customer name.

This Code:

$db = new mysqli("localhost","root","","test");

// Query Customer & Transaction No (First Foreach)
$sql_1 = "SELECT nama FROM pesan GROUP BY nama";
$result = $db->query($sql_1);

$no = 1;
foreach($result as $row){
echo $row['nama'].'<br>';
echo ' Transaction No ='.$no++.'<br>';
}

// Query Purchased product details (second Foreach)
$sql_2 = "SELECT product,nama FROM buy";
$result = $db->query($sql_2);

foreach($result as $row){
  echo $row['nama'].'<br>';
  echo 'Product Name  ='.$row['product'].'<br>';
  echo 'Transaction No ='.$no++.'<br>'; // transaction no is taken the value of $no++ from the foreach above based on customer name.
  }

Result From First Foreach:

farez
Transaction No =1
hardy
Transaction No =2

Result From Second Foreach:

  farez
  Product Name = TV 
  Transaction No = 1
  hardy
  Product Name = radio 
  Transaction No = 2

Upvotes: 0

Views: 147

Answers (1)

JamalThaBoss
JamalThaBoss

Reputation: 404

you can actually do that in various ways;

One of them is creating an array and holding the name and transaction number in it as $name => $transaction_number form. To do this you can simply change your first foreach to:

/*----- Define Array Here ------*/
    $trnoArr = array();

/*----- Define Transacrion Number And Loop through your results------*/
    $no = 1;
    foreach($result as $row){

        /*----- Add your rows to array ------*/
            $trnoArr[$row['nama']] = $no;

        /*----- Echo Your results ------*/
            echo $row['nama'].'<br>';
            echo ' Transaction No ='.$no.'<br>';

        /*----- Increase Number Value ------*/
            $no++;

    }

Than in your second loop you can simply get the transaction number from freshly created array like:

foreach($result as $row){
    echo $row['nama'].'<br>';
    echo 'Product Name  ='.$row['product'].'<br>';
    echo 'Transaction No ='.$trnoArr[$row['nama']].'<br>'; // Like here
}

Upvotes: 0

Related Questions