php - How to check if date in associative array and use value associated to this date With SQL Query (Mysql)

I have an associative array as follows:

$ a = 
[ 
  "2023-05-18" => 10.0
  "2023-07-14" => 2.0
  "2023-11-01" => 16.0
  "2023-11-11" => 2.0
  "2023-12-25" => 8.0
  "2024-01-01" => 2.0
  "2024-04-01" => 22.0
]

And in a SQL query i want to do something like:

function ($a) {
     $sql = " ... some code before ...

              IF (table.date IN ($a), value of date (ex 10.0), 1)
            "
          ;
}

Not only with if with case when, or whatever the idea is to get the value in associative array according to the date (if it exist in the array);

Answer

Solution:

I think the better way to do that is to concatenate the logic with your query and use a case when to handle that. something like

$s= "*\nCASE\n";

foreach ($yourArray as $dateKey => $dateValue) {
    $s .= "WHEN DATE_FORMAT(table.date, '%Y-%m-%d') = '" . $dateKey . "' THEN 
          " . $dateValue . " \n"
    ;
}

$s .= "END\n";

And in you query you can directly do something like

    "query do something
         ". $s ."
      do something again "

I hope this would help

Answer

Solution:

Your description of what you want is not very clear, but from the conversation and a bit of assumption I think it probably boils down to:

"list all the values from the PHP array where the date key matches at least one row from the SQL table"

If so, then here's one way you could do it:

  • Run a query which returns a distinct list of dates from the table where the date matches one of the keys in the array. This effectively gives you a list of dates which appear in both the array and the database.
  • Loop through that list to show the values matching those array keys.

Now here's some sample code. There may be a more efficient way to do it, but this is my initial thought:

$a = 
[ 
  "2023-05-18" => 10.0,
  "2023-07-14" => 2.0,
  "2023-11-01" => 16.0,
  "2023-11-11" => 2.0,
  "2023-12-25" => 8.0,
  "2024-01-01" => 2.0,
  "2024-04-01" => 22.0
];

$dates = array_keys($a);
$params = array_fill(0, count($dates), "?");

//sql to get all rows from database which match dates in the array
$sql = "SELECT `date` from `table` WHERE `date` IN (".implode(",", $params).")";
echo $sql; //just for debugging

//let's assume you're using PDO and have a connection object named $pdo, for the sake of argument
$stmt = $pdo->prepare($sql);
$result = $pdo->execute($dates);
$data = $result->fetchAll(PDO::FETCH_ASSOC);

//loop the returned set of matching dates
foreach ($data as $row)
{
    //output values from the original array which match the dates returned from the database
    echo $a[$row["date"]].PHP_EOL;
}

Related documentation:

Source