【问题标题】:How to store string variables in php array如何在php数组中存储字符串变量
【发布时间】:2016-10-09 10:37:29
【问题描述】:
$matrix=array($_SESSION['review_buffer_name'],$_SESSION['review_buffer_mail'],$_SESSION['review_buffer_comment']);

上面这行代码在WHILE循环里面,所以它存储了多个数组的记录。存储记录的方法是否正确?我们如何访问矩阵的每条记录和值?

$matrix 应该存储多行数组...问题是当我访问 $matrix[2] 时,它会给出数组的第二个值...而不是数组的第二个记录

【问题讨论】:

  • 分享你的while循环?你到底想做什么?描述$matrix数组的使用。
  • $matrix 应该存储多行数组...问题是当我访问 $matrix[2] 然后它给出数组的第二个值...而不是数组的第二个记录
  • 这是因为您的 $matrix 是一个常用列表,而且您似乎没有在结果集合中添加任何内容。如果该特定语句在您的while 中,您总是重写$matrix 变量。尝试使用$matrix[] = [ ... ]; 看看有什么变化或分享更多您的代码。

标签: php mysql arrays session-variables


【解决方案1】:

你可以试试:

//Before while loop declare the array variable
$matrix = array();

While(your condition){
    $matrix[] = array(
           $_SESSION['review_buffer_name'],
           $_SESSION['review_buffer_mail'],
           $_SESSION['review_buffer_comment']
   );
}

//To access array:

print_r($matrix[0]); //print_r whole first row. (array start from 0)
echo $matrix[0][0]; //echo single data that first row's first data

或者您可以将索引设置为如下名称:

//Before while loop declare the array variable
$matrix = array();

While(your condition){
    $matrix[] = array(
           'review_buffer_name'=>$_SESSION['review_buffer_name'],
           'review_buffer_mail'=>$_SESSION['review_buffer_mail'],
           'review_buffer_comment'=>$_SESSION['review_buffer_comment']
    );
    }

//Then access array:

print_r($matrix[0]); //print_r whole first row. (array start from 0)
echo $matrix[0]['review_buffer_name']; // first row's first data

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-20
    • 2016-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-14
    • 1970-01-01
    相关资源
    最近更新 更多