我无法从我的多维数组中获得任何输出。我正在尝试使用 push_array 方法获取我的数据。
我想得到我的输出:
- 约翰,1001
- 汤姆,1002
- 杰里,1003
- 萨拉,1004
但是,我没有得到任何输出。我知道数组正在工作,因为当我回显 $message 并且不在我的输出 foreach 数组中使用 $id 和 $name 时,我得到以下输出。
当前输出:(回显 $message 时)
- 1
- 2
- 3
- 4
但是当我使用 $id 和 $name 时没有显示任何内容,如下所示。
<ul class="result"><?php
foreach ($output as $message) {
$id = $message[1][0];
$name = $message[1][1];
?><li>
<a href="handleDownload.php?id=<?php echo $id;?>"><?php echo $name; ?> </a>
</li><php } ?>
</ul>
这是我的完整代码:
<?php
$Download = new Download();
$result = array(); //store results of upload
try {
$Download->showDBFiles();
$output = $Download->getMessages();
} catch (Exception $e) {
$result[] = $e->getMessage();
}
?>
<h2>Output</h2>
<?php if ($output) { ?>
<ul class="result">
<?php foreach ($output as $message) {
$id = $message[1][0];
$name = $message[1][1];
?>
<li><a href="handleDownload.php?id=<?php echo $id;?>"><?php echo $name; ?></a></li>
<?php } ?>
</ul>
<?php } ?>
定义数组的函数
protected $messages = array();
public function showDBFiles() {
global $database;
$values=array();
$sql = "SELECT resume_id, resume_title FROM ".self::$table_name;
$result = $database->query($sql);
if(mysqli_num_rows($result)==0){
$this->messages[] = "Database is empty";
}else{
while(list($id, $name) = mysqli_fetch_array($result)){
array_push($this->messages, array($id, $name));
}
}
}
public function getMessages()
{
return $this->messages;
}
更新: 在使用了 jedrzej.kurylo 的建议后,我的 var_dump 输出中显示了 $id 和 $name 值:
array(4) { [0]=> array(2) { [0]=> string(2) "73"[1]=> string(2) "qd"} [1]=> array( 2) { [0]=> string(2) "72"[1]=> string(3) "jav"} [2]=> array(2) { [0]=> string(2) "70"[1]=> string(4) "da12"} [3]=> array(2) { [0]=> string(2) "71"[1]=> string(3) "jav"} }
但是由于某些原因,我不确定我的输出现在是这样的:
- d
- 一个
- 一个
- 一个
最佳答案
问题在于您如何在此处使用 array_push:
$this->messages[] = array_push($values, array($id, $name));
array_push 不返回更新后的数组,而是返回数组中新的项目数 - 参见 http://php.net/manual/en/function.array-push.php .这就是您在输出中获得越来越多整数的原因。
改为执行以下操作:
while(list($id, $name) = mysqli_fetch_array($result)){
array_push($this->messages, array($id, $name));
}
或者只是
while(list($id, $name) = mysqli_fetch_array($result)){
$this->messages[] = array('id'=>$id, 'name'=>$name);
}
然后你可以像这样访问$id和$name:
$id = $message['id'];
$name = $message['name'];
关于php - 无法输出多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31702980/