php - PHP:如何获取数组的特定值
问题描述
我想在我的 phpmyadmin 表中获取特定值的 id。所以,我有一张表,其中“id_cal”作为 AI id,“mois”用数字表示月份(例如 1 表示一月),“annee”表示年份。(见日历表)
我正在尝试为月份和年份设置 php 变量,如果它们与当前月份和年份匹配,我想获得这个特定的 id。
我评论了我遇到麻烦的php代码,这里是:
<?php
include_once('config.php');
$m = idate('n');
$y = idate('Y');
echo $m; echo "\t"; echo $y; echo "<br>"; echo "<br>"; // The result of this is 7 2019
$reponse = $bdd->query('SELECT * FROM calendrier');
while($donnees= $reponse->fetch()){
$mois = $donnees['mois'];
$year = $donnees['annee'];
$id_cal = $donnees['id_cal'];
echo $id_cal;
echo "\t";
echo $mois;
echo "\t";
echo $year;
echo "<br>";
}
// What I am trying to do :
if (($m = $mois) && ($y = $year)){ // If the month and the year are the current month/year
$i = $id_cal; // I want to put the id refering to the current month/year (in my phpmyadmin table) into a new variable
echo "<br>"; // and echo this variable (or use it in other ways)
echo $i; // BUT what I am echoing is 24 representing the number of values in my array
} // How can I only get 7 ? (in this exemple, since we are the 7/2019)
这是我在本地主机中得到的:echo
我真的不明白为什么我没有7。
另外,我尝试了这个而不是我的while:
$donnees= $reponse->fetch();
$mois = $donnees['mois'];
$year = $donnees['annee'];
$id_cal = $donnees['id_cal'];
// But in this cas I am having $i = 1, so it's the same problem.
非常感谢您的回复,我对此感到很挣扎。
解决方案
这是因为在您的 while 语句的每次迭代中id_cal
都会被新值覆盖。id_cal
为了得到你想要的结果,你可以把 if 放在 while 语句中......
while($donnees= $reponse->fetch()){
$mois = $donnees['mois'];
$year = $donnees['annee'];
$id_cal = $donnees['id_cal'];
echo $id_cal;
echo "\t";
echo $mois;
echo "\t";
echo $year;
echo "<br>";
if (($m == $mois) && ($y == $year)){
$my_var_to_use_elsewhere = $id_cal;
}
}
echo "<br>";
echo $my_var_to_use_elsewhere;
推荐阅读
- macos - 除了最后 n 行之外,如何在 Mac OS X 的终端中清除以前的输出?
- virtual-machine - 如何访问 VMWare Fusion VM 内的 VPN
- python - 工厂设计模式:继承 vs 委托 vs 模块级函数
- python - 网络和属性(节点 - 邻居)
- java - Java ZipInputStream 在线程中中断,但不在主线程中
- javascript - 如何将提交按钮的值从另一个组件传递到 FinalForm?
- bash - How do I use conditions in a read -r command bash-script?
- python - beautiful soup parse table columns and stripping newlines
- html - 如何使用 flexbox 实现只有一个孩子(前一个)响应
- python - 将日期列(字符串)转换为日期时间并匹配格式