【问题标题】:Why the 2d array treatment in PHP isn't good?为什么 PHP 中的二维数组处理不好?
【发布时间】:2017-11-28 14:11:30
【问题描述】:

我正在尝试使用两个不同的查询在 PHP 中构建一个带有两个循环的二维数组。 由于某种原因,该页面没有显示任何有关发生的任何错误的消息。 它的反应就像数组不存在一样。

因此我假设它是因为我没有正确处理数组。

这是代码:

$stuarr= array();        ***//the 2d array initialization***

$query1 = "SELECT * FROM students WHERE userid= '$uid' ORDER BY name"; 
$stulist = mysqli_query($conn,$query1) or die ("cannot query the table1 " .mysqli_error($conn)); 
while ($students = mysqli_fetch_array($stulist)) {
    ${$students['name']}= array();   ******//the inside array initialization...the one that will insert to $stuarr***

    $count=$_SESSION['counter'];
    $sname=$students['name'];
    $query3 = "SELECT * FROM ranks WHERE userid= '$uid' AND rankers='$sname' ORDER BY therate DESC"; 
    $stur = mysqli_query($conn,$query3) or die ("cannot query the table1 " .mysqli_error($conn));
    while ($sturank = mysqli_fetch_array($stur) && !$count==0) {

        array_push(${$students['name']},$sturank['rated']);
        $count=$count-1;
        print_r(${$students['name']});
    }

    array_push($stuarr,${$stulist['name']});
    print_r($stuarr);  ***///this print is showing nothing***
}

我很想听听您对代码的看法。

谢谢!

【问题讨论】:

  • 为什么要使用这样的变量变量?只需执行$student = array();,将数据放入其中,然后以$stuarr[] = $student; 结束...
  • 我不确定你是否理解 ${$students['name']} 实际在做什么。
  • @PatrickQ 太好了,那你解释一下吧。
  • $students['name'] 是查询中的一个字段,我想为每个名称启动一个新 var...

标签: php arrays


【解决方案1】:

改变

array_push($stuarr,${$stulist['name']});

进入

array_push($stuarr,${$students['name']});

【讨论】:

  • 为什么是这样的解决方案,请解释一下。
  • 谢谢你,它正在工作,但不像我预期的那样......它打印了: Array ( [0] => Array ( [0] => [1] => [2] => ) [ 1] => 数组 ( [0] => [1] => [2] => ) [2] => 数组 ( [0] => [1] => [2] => ) ) 它插入 o, 1,2 值而不是真正的值
猜你喜欢
  • 1970-01-01
  • 2014-07-13
  • 1970-01-01
  • 1970-01-01
  • 2021-12-28
  • 1970-01-01
  • 2017-09-20
  • 1970-01-01
相关资源
最近更新 更多