I know that this is not the best way or proper way but could use an explanation why this does not work. The same code works if I do not put it in a class. The test.php shows shows the array but I can not get it to display the array. A good example would be greatly appreciated.
<?php
class Photo
{
public $id;
public $categories;
public $img_name;
public $myArray = array();
public function findAll()
{
$dbConnection = mysqli_connect("localhost", "root", "root", "gallery");
$query = "SELECT * FROM images";
$st开发者_如何转开发mt = mysqli_prepare($dbConnection,$query);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $id, $categories,$img_name);
while(mysqli_fetch($stmt)) {
array_push($this->myArray,$id);
}
return $this->myArray;
}
}
?>
test.php
<?php
require_once ('photo.php');
$obj = new Photo();
$obj->findAll();
echo "<pre>";
var_dump($obj);
echo "</pre>";
foreach ($obj as $val) {
echo "$val <br/>";
}
?>
and when I run the page I get
object(Photo)#1 (4) {
["id"]=>
NULL
["categories"]=>
NULL
["img_name"]=>
NULL
["myArray"]=>
array(10) {
[0]=>
int(447)
[1]=>
int(448)
[2]=>
int(449)
[3]=>
int(439)
[4]=>
int(440)
[5]=>
int(435)
[6]=>
int(431)
[7]=>
int(432)
[8]=>
int(433)
[9]=>
int(434)
}
}
Array
You're var_dumping the object, not the array.
This will work:
require_once ('photo.php');
$obj = new Photo();
foreach ($obj->findAll() as $val) {
echo "$val <br/>";
}
Or indeed:
$items = $obj->findAll();
foreach($items as $val)
{
echo $val . '<br />';
}
in test.php you are not doing mistake of assignment. You are not assigning the value of $obj->findAll();
Change test.php like this
<?php
require_once ('photo.php');
$obj = new Photo();
$array=$obj->findAll();
echo "<pre>";
var_dump($array);
echo "</pre>";
foreach ($array as $val) {
echo "$val <br/>";
}
?>
Replace
foreach ($obj as $val) {
by
foreach ($obj->myArray as $val) {
or by
foreach ($obj->findAll() as $val) {
You're trying to iterate through an object, as described in php manual.
That way you iterate through every property in the object, so $val takes the value of $id, $categories, $img_name and $myArray, in that order. Your echo statement makes 3 newlines to appear (as the first 3 properties are null, and null in string context is converted to the empty string) and the "Array" word followed by a newline (because that's the way an array is converted to string context).
You may want to iterate through the array itself, then use any of the other answers.
精彩评论