I am learning how to use multidimension arrays in PHP and I need help to output the values.
The error i get is:
Warning: Illegal string offset 'name'in C on line 35.
I want to output the values like this:
name quantity
church 1
Here is my code:
<?php
session_start();
if (!isset($_SESSION['images'])) {
$_SESSION['images'] = array();
}
if (isset($_POST['submit'])) {
$test[]= $_POST['name'];
$test[]= $_POST['qty'];
$_SESSION['images'][] = $test;
}
foreach ($_SESSION['images'] as $nom) {
foreach ($nom as $val) {
echo $val["name"];
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Test Array</title>
</head>
<body>
<div id="holder">
<p>You have <?php echo count($_SESSION['images']);?> images</p>
<div class="test">
<div><img src="images/church.jpg"></div>
<br>
<form action="multidimention_array.php" method="post">
<input type="hidden" name="name" id="name" value="church">
<input type="text" name="qty" id="qty" size="1" value="1">
<input type="submit" name="submit" id="submit" value="Send Value">
</form>
</div>
<div class="test">
<div><img src="images/stellar.jpg"></div>
<br>
<form action="multidimention_array.php" method="post">
<input type="hidden" name="name" id="name" value="stellar">
<input type="text" name="qty" id="qty" size="1" value="1">
<input type="submit" name="submit" id="submit" value="Send Value">
</form>
</div>
</div>
</body>
</html>
答案 0 :(得分:0)
$_POST['name']
is being assigned to an integer index in $test
and then $_SESSION['images'][]
so 'name'
doesn't exist as a key when you loop.
Try the following:
$test['name'] = $_POST['name'];
$test['qty'] = $_POST['qty'];
UPDATE
Why are you doing two foreach
s? The first will loop through the session images, which is an array containing your test array. The second loops through your test array. At this point, you are already in the $test['name']
var, so you are effectively calling $_SESSION['images'][0]['name']['name']
:
Try the following:
foreach ($_SESSION['images'] as $image) {
echo $image['name'];
}
答案 1 :(得分:0)
The problem is here:
$test[]= $_POST['name'];
This does not mean take the value for the key name
from $_POST
and save it under the same key in $test
. What it means is take the value for the key name
from $_POST
and save it under the first key that is free. In practice that means it will end up with key 0
(asuming $test
was empty to begin with). So there will be no $test['name'], and therefore no $_SESSION['images']['name']
and no $val['name'];
The code you need to use is this:
$test['name'] = $_POST['name'];
$test['qty'] = $_POST['qty'];