Unable to output multidimensional array
I cannot get any output from my multidimensional array. I am trying to get my data using push_array method.
I would like to receive my output as:
- John, 1001
- Volume 1002
- Jerry, 1003
- Sarah, 1004
However, I am not getting any output. I know the array works, although I get the following output when I echo $ message and don't use $ id and $ name in my foreach array of output.
Current output: (on echo $ message)
- 1
- 2
- 3
- 4
But nothing is displayed when I use $ id and $ name as shown here.
<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>
Here is my complete code:
<?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 } ?>
The function in which the arrays are defined
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;
}
UPDATE: After using jedrzej.kurylo's suggestion, I can have $ id and $ name values as shown in my var_dump output:
array (4) {[0] => array (2) {[0] => string (2) "73" [1] => string (2) "qd"} [1] => array (2) { [0] => line (2) "72" [1] => line (3) "jav"} [2] => array (2) {[0] => line (2) "70" [1] => string (4) "da12"} [3] => array (2) {[0] => string (2) "71" [1] => string (3) "jav"}}
However for some reason I'm not sure about my output, now this:
- d
- and
- and
- and
source to share
The problem is how you use array_push here:
$this->messages[] = array_push($values, array($id, $name));
array_push does not return the updated array, but the new number of elements in the array - see http://php.net/manual/en/function.array-push.php . This is why you are getting integers in your issue.
Do the following:
while(list($id, $name) = mysqli_fetch_array($result)){
array_push($this->messages, array($id, $name));
}
or simply
while(list($id, $name) = mysqli_fetch_array($result)){
$this->messages[] = array('id'=>$id, 'name'=>$name);
}
Then you can access $ id and $ name like this:
$id = $message['id'];
$name = $message['name'];
source to share