I’m trying to take parts number from two different tables and put them in the same array, then rearrange them.
Strangely it gives parts number twice, but when I run the same query in phpmyadmin it gives each part number once. I spend whole day but could not correct this.
//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;
}
//second query
$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;
}
/// rearanging data……
$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;
}
}
//output result
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>";
}
RESULT
1 10R46 2
2 10R46 2
3 10R91 1
4 10R91 1
5 10M95 3
6 10M95 3
What i want:
1 10R46 2
2 10R91 1
3 10M95 3
First query print_r($finalData);
Array (
[10R46 ] => Array ( [0] => Array ( [part_no] =>
10R46 [sale_qty] => 1 ) )
[10R91 ] => Array ( [0] => Array ( [part_no] =>
10R91 [sale_qty] => 3 ) ))
3
Answers
Because, you are looping twice:
Modify
To:
I think your problem lies within the $finalData where you store same results twice. (ofcourse from different tables though).
the first query creates a result of
then you run the second query and ADD to the finaldata again with this
$finalData[$row['part_no']][] = $row;
so the $finalData is now something like
That is the reason why you double loop it and also get double results.
So i would combine the queries.
and now your result should look something like this without the secondquery
also if you don’t expect there would be two rows with same part_no you can change
So you don’t need to double loop it.
Remove the duplicates and rearrange the keys (if needed) before you put your array in the
foreach
.Then you can use the
$new_array
to generate your html