首页 > 解决方案 > 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.

非常感谢您的回复,我对此感到很挣扎。

标签: phpmysql

解决方案


这是因为在您的 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;

推荐阅读