gpt4 book ai didi

php - 两个 while 循环到单个数组?

转载 作者:行者123 更新时间:2023-11-29 16:13:17 27 4
gpt4 key购买 nike

我试图从两个不同的表中获取零件编号并将它们放入同一个数组中,然后重新排列它们。

奇怪的是,它给出了零件编号两次,但是当我在 phpmyadmin 中运行相同的查询时,它给出了每个零件编号一次。我花了一整天但无法纠正这个问题。

//first query

$finalData = array(); $sql="SELECT
jobc_parts_p.part_no,
SUM(jobc_parts_p.issued_qty) AS sale_qty FROM
`jobc_parts_p` WHERE DATE_FORMAT(jobc_parts_p.date_time,'%Y-%m-%d') BETWEEN '".$f."' AND '".$t."'

GROUP BY jobc_parts_p.part_no";


$result = $conn->query($sql);
while($row = $result->fetch_assoc()){
$finalData[$row['part_no']][] = $row;
}

//第二个查询

  $sql2="SELECT
jobc_consumble_p.part_no,
SUM(jobc_consumble_p.issued_qty) AS csale_qty
FROM
`jobc_consumble_p`
WHERE DATE_FORMAT(jobc_consumble_p.date_time,'%Y-%m-%d') BETWEEN '".$f."' AND '".$t."'
GROUP BY
jobc_consumble_p.part_no";

$result = $conn->query($sql);
while($row = $result->fetch_assoc()){
$finalData[$row['part_no']][] = $row;
}

///重新排列数据......

$rearrangedFinalData = array();
foreach($finalData AS $first) {
foreach($first AS $data) {
$temp = array();
$temp['part_no'] = $data['part_no'];
$temp['sale_qty'] = isset($data['sale_qty']) ? $data['sale_qty'] : $data['csale_qty'];
$rearrangedFinalData[] = $temp;
}
}

//输出结果

foreach($rearrangedFinalData AS $row) {
$sr++;


echo "<tr><td>$sr</td>
<td colspan='2' >",$row["part_no"],"</td>
<td align='center'>",$row["sale_qty"],"</td>
</tr>";
}

结果

1    10R46    2
2 10R46 2
3 10R91 1
4 10R91 1
5 10M95 3
6 10M95 3

我想要什么:

1    10R46    2
2 10R91 1
3 10M95 3

第一个查询 print_r($finalData);

Array ( 
[10R46 ] => Array ( [0] => Array ( [part_no] =>
10R46 [sale_qty] => 1 ) )
[10R91 ] => Array ( [0] => Array ( [part_no] =>
10R91 [sale_qty] => 3 ) ))

最佳答案

因为,您循环了两次:

修改

$rearrangedFinalData = array();
foreach($finalData AS $first) {
foreach($first AS $data) { // <-- Remove this extra loop.
$temp = array();
$temp['part_no'] = $data['part_no'];
$temp['sale_qty'] = isset($data['sale_qty']) ? $data['sale_qty'] : $data['csale_qty'];
$rearrangedFinalData[] = $temp;
}
}

致:

$rearrangedFinalData = array();
foreach($finalData AS $first) {
$temp = array();
$temp['part_no'] = $first['part_no'];
$temp['sale_qty'] = isset($first['sale_qty']) ? $first['sale_qty'] : $data['csale_qty'];
$rearrangedFinalData[] = $temp;
}

关于php - 两个 while 循环到单个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55063222/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com