php - Merge two arrays and loop through them to return all the elements

333

I have two queries that return 5 rows of data from each query. I then merge the resulting arrays to create one array.

If I were using just one arry I would do it like this:

mysql_select_db($database_iMaint, $iMaint);
$query_WaterHot = sprintf("SELECT h.UniqueID, h.Room, h.AuditBy,  h.AuditDate, h.SeqID, h.WaterHot 
FROM NXLHR_Hist h 
WHERE (h.WaterHot IS NOT NULL OR
       h.WaterHot IS NOT NULL
      ) 
      AND 
      h.CompStamp >=  DATE('".$_POST['FromDate']."') 
      AND 
      h.CompStamp <= DATE('".$_POST['ToDate']."') 
ORDER BY h.Room ASC 
");
$WaterHot = mysql_query($query_WaterHot, $iMaint) or die(mysql_error());
$row_WaterHot = mysql_fetch_assoc($WaterHot);
$totalRows_WaterHot= mysql_num_rows($WaterHot);


do {

    echo $row_WaterHot['Room'];
    echo $row_WaterHot['WaterHot'];
    echo $row_WaterHot['WaterCold'];

} while ($row_WaterHot = mysql_fetch_assoc($WaterHot));

Above is how I would normally process the data but in this case I am using the results from two queries which is why I am merging them.

So I now need to loop through the merged array and output each of the values.

$row_WaterHot = mysql_fetch_assoc($Waterhot); // five records
$row_WaterCold = mysql_fetch_assoc($WaterCold); // five records
$Water = array();
$Water = array_merge($row_WaterHot, $row_WaterCold);

foreach ($Water as $key => $value) {

// how do I echo the results of each value like this
echo "the name of the $key and the $value

} 

Or should I be doing this another way?

Thanks in advance for your help and time.

109

Answer

Solution:

Simply use a foreach This is pretty easy to use. The template looks like this :

foreach($array as $key=>$value){
}

In your case, you would have something like this

  foreach($Water as $key=>$val)
        echo $val;

People are also looking for solutions to the problem: javascript - Data not returning Ajax

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.