Skip to content
Advertisement

How to insert the php array into another array using a loop?

<?php
 include_once("connect.php");
$query = "
select date, sum(amount) as total
from expenses
where date <= NOW()
and date >= Date_add(Now(),interval - 7 day)
group by date;";
    $dateArray = Array();
    $result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) > 0) {
  // output data of each row
  while($row = mysqli_fetch_assoc($result)) {
    echo $row["total"];
    echo $row["date"];
      array_push($dateArray,$row);
  }}

echo $dateArray[0]["total"];
$dataPoints = array(
    array("y" => 25, "label" => "Sunday"),
    array("y" => 15, "label" => "Monday"),
    array("y" => 25, "label" => "Tuesday"),
    array("y" => 5, "label" => "Wednesday"),
    array("y" => 10, "label" => "Thursday"),
    array("y" => 0, "label" => "Friday"),
    array("y" => 20, "label" => "Saturday")
);
 
?>

I tried to run it like this and got an error, so not sure if I can set each of the array elements “y” as one of the amounts and “label” as a unique date like this

$dataPoints = array(

foreach($dateArray as $item) {
 array("y" => $dateArray("amount"), "label" => $dateArray("date"))
}
)

Advertisement

Answer

Try it as following:

$dataPoints = array();
foreach($dateArray as $item) {
    array_push($dataPoint, array("y" => $dateArray("amount"), "label" => $dateArray("date")));
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement