[英]How to get value numbering ($no++) in foreach php?
i have 2 foreach with different query.我有 2 个具有不同查询的 foreach。 The first foreach displays the customer name and transaction number.
第一个 foreach 显示客户名称和交易编号。
Transaction number value in the first foreach is not from Database but from looping $no++.第一个 foreach 中的事务编号值不是来自数据库,而是来自循环 $no++。
How to get $no++ value from first foreach to store in second foreach based on customer name.如何根据客户名称从第一个 foreach 获取 $no++ 值以存储在第二个 foreach 中。
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:第一次 Foreach 的结果:
farez
Transaction No =1
hardy
Transaction No =2
Result From Second Foreach:第二次 Foreach 的结果:
farez
Product Name = TV
Transaction No = 1
hardy
Product Name = radio
Transaction No = 2
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.其中之一是创建一个数组并将名称和交易编号保存为 $name => $transaction_number 形式。 To do this you can simply change your first foreach to:
为此,您只需将第一个 foreach 更改为:
/*----- 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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.