【问题标题】:Array changes value after exiting loop退出循环后数组更改值
【发布时间】:2016-09-18 10:55:23
【问题描述】:

我使用 while 循环从数据库中获取值并将它们分配给数组。但是,当退出循环时;值改变。

$i=1;

$sql = "SELECT * FROM opportunities WHERE location = '$location'";
$result1 = mysqli_query($conn, $sql);
while($row1 = mysqli_fetch_assoc($result1)) 
{
 $job[$i]= $row1['id'];
 echo $job[$i] . "is the ID of the Job opening with this location <br>";

  $job[$i][1] = 3;
  $i=$i+1;
  echo $job['$i'];


}

echo $job[1]. $job[2];

当我在循环中时,job["i"] 返回一个不同的值给第二个实例。先感谢您。根据 cmets 的要求分享更多代码

$sq4 = "SELECT * FROM opportunities WHERE skill1 = '$skill'";
$result4 = mysqli_query($conn, $sq4);
while($row4 = mysqli_fetch_assoc($result4)) 
{$id4=$row4['id'];
echo $id4 . "is the ID of the Job opening matching the skill you entered as the most important skill<br>";
 $job[$i]= $row4['id'];
 $job[$i][1] = 3;
  $i=$i+1;}

输出:对于第一个循环,循环中的结果(第一个实例)是 27 和 29。 在循环之外,结果是 23 和 23。23 是下一个循环的第一个值(如果以任何方式相关)

【问题讨论】:

  • 预期输出和当前输出是多少?
  • 你不需要索引中的双引号,你需要在job之前加一个$
  • @RST 在复制代码时出错。更正了它。谢谢指出
  • @u_mulder 此循环之外还有其他循环。 (我刚刚复制了其中的一部分。)如果有帮助,23 是下一个循环的第一个值。编辑了问题。请看一下
  • 你为什么要$job[$i][1] = 3;

标签: php arrays mysqli


【解决方案1】:

以下代码的结果是什么?

$sql     = "SELECT * FROM opportunities WHERE location = '$location'";
$result = mysqli_query($conn, $sql);
$jobs    = array();
$i      = 0;

while ($row = mysqli_fetch_assoc($result)) 
{
    $jobs[$i]['id']        = $row['id'];
    $jobs[$i]['relevance'] = 3;

    $i++;
}

var_dump($jobs);

【讨论】:

  • 这可行,但不明白为什么我的不行:-O
猜你喜欢
  • 1970-01-01
  • 2023-02-22
  • 2013-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多