Big array, problems echoing it out - php

I got this problem trying to echo out a big array.
print_r looks like this:
http://codepaste.net/5js97a
There's no problem echoing out the first 2 rows like this in a foreach loop:
$item['name'], but for the rest of them deeper inside the array, I just get an error.
Thanks!
Code:
function categories($parent = NULL) {
$query = $this->db->where('parent_id', $parent)->get('categories');
$results = $query->result_array();
foreach($results as $result) {
$child_array = Forummodel::categories($result['id']);
if(sizeof($child_array) == 0) {
array_push($results, $result['name']);
} else {
array_push($results, array($result['name'], $child_array));
}
}
return $results;
}
Im also using codeigniter

You are iterating on an increasing array. Here is your code:
function categories($parent = NULL) {
$query = $this ->db ->where('parent_id', $parent) ->get('categories');
$results = $query->result_array();
foreach($results as $result) {
$child_array = Forummodel::categories($result['id']);
if(sizeof($child_array) == 0) {
array_push($results, $result['name']);
} else {
array_push($results, array($result['name'], $child_array));
}
}
return $results;
}
The foreach is iterating down the array $results and you are adding to it with each loop, plus, by the time you hit an iteration where $result doesn't contain 'id' or 'name' you are probably getting the error. You might want to put the child arrays into another array and merge them after the foreach loop if you still want to do that.

Related

Retrieve data with foreach from return array function

I'm having troubles with my function and how to retrieve the data. Here is what i got.
public function getImages()
{
$array = array();
//Test query
$query = $this->connect()->query("SELECT * from user");
while ($row = $query->fetch()) {
$array[] = $row;
return $array;
}
}
Now I'm calling this function but i can not use foreach to access the array.
include "header.html";
include "autoload.php";
spl_autoload_register('my_autoloader');
$users = new User;
$users->getImages();
foreach ($users as $value) {
echo $value["username"];
}
What am I doing wrong? I'm only getting one result but there are many in my database. Or if i call the $array in foreach it says undefined.
A couple things. First, your function is only ever returning an array with one element in it. If you want to finish populating the array, don't return until after the loop:
while ($row = $query->fetch()) {
$array[] = $row;
}
return $array;
And second, you're trying to iterate over the object which has the function, not the value returned from the function. Get the return value and iterate over that:
$userDAO = new User;
$users = $userDAO->getImages();
foreach ($users as $value) {
echo $value["username"];
}
You just need to put the return statement out of the while loop.
public function getImages() {
$array = array(); //Test query
$query = $this->connect()->query("SELECT * from user");
while ($row = $query->fetch()) {
$array[] = $row;
}
return $array;
}

How do I build this array to output?

I have the following function which fetches some data from a MySQL table:
function readQuestion ($quizType, $questionId) {
$data = array();
$query = $this->dbConnection->query("SELECT * FROM $quizType WHERE id = $questionId");
foreach ($query as $row) {
var_dump($row);
};
echo $data
}
How can I push all the returned data into an array, where each member is indexed by a number?
Do I need to use echo or return at the end? They seem to have the same effect.
EDIT: Is this the correct way of returning results of the query? I am passing it to the front-end.
$questionData = $controller->readQuestion($quizType, $questionId);
return $questionData;
In general your function must looks like:
function readQuestion ($quizType, $questionId) {
$data = array();
$query = $this->dbConnection->query("SELECT * FROM $quizType WHERE id = $questionId");
return $query;
}
But, you have to look what is inside $query variable. If it is array - just return this array, if not - maybe it is some iterator, hence you have to check it and try to find method like toArray or something like that... Otherwise, you have to do something like:
$data = [];
foreach ($query as $row) {
$data[] = $row;
};
return $data;
Now you can use this function like:
var_dump(readQuestion($quizType, $questionId));
Take a look up here on how to secure your data.
Anyway, as I said in the comment you cannot use echo on an Array. And you can't do anything with the output of var_dump.
Change var_dump($row); for $data[] = $row;
and change echo $data; for return $data;
function readQuestion ($quizType, $questionId) {
$data = array();
$query = $this->dbConnection->query("SELECT * FROM $quizType WHERE id = $questionId");
foreach ($query as $row) {
$data=$row;
};
return $result;
}

Only last element stores in array in CI

I'm using array in ci . whenever i store i can get only the last elements ! other elements are overwrite.
this is my code
$table="wp_term_taxonomy";
$data=array();
$this->db->where('taxonomy','Geographical');
$query = $this->db->get($table);
if ($query->num_rows() > 0)
{
foreach ($query->result() as $value) {
$terms_id=$value->term_id;
$table2="wp_terms";
$this->db->where('term_id',$terms_id);
$query2 = $this->db->get($table2);
if ($query2->num_rows() > 0)
{
foreach ($query2->result() as $value2) {
$data['name']=$value2->name;
$data['id']=$value2->term_id;
}
}
}
}
var_dump($data);
return $data;
}
i get only the last element in $data array
You are overriding values. Try it like this:
foreach ($query2->result() as $value2) {
$data[]=array('name' => $value2->name, 'id' => $value2->term_id);
}
try this:
foreach ($query2->result() as $value2) {
$data[]['name']=$value2->name;
$data[]['id']=$value2->term_id;
}

Rewrite mysqli_fetch_all() to get the same result

Since the servers version is older than 5.3.0, I need to rewrite the following piece of function to do the same as it does now:
else {
$res = mysqli_query($_con, "SELECT * FROM house");
$row = mysqli_fetch_all($res, MYSQLI_ASSOC);
return $row;
}
In html I call it like this:
$results = getResults();
foreach ($results as $value) {
echo $value['Title']." / "; echo $value['Version'];
}
How can I call the results in my html the same way but with different function?
EDIT: I want to get all of the results from table "house" but without the use of function mysqli_fetch_all()
It's just a simple loop that calls mysql_fetch_array() and collects all the rows in an array.
function mysqli_fetch_all($res, $mode) {
$array = array();
while ($row = mysql_fetch_array($res, $mode)) {
$array[] = $row;
}
return $array;
}

Echo values of arrays?

I want to echo the values of all arrays that has been returned from a search function. Each array contains one $category, that have been gathered from my DB. The code that I've written so far to echo these as their original value (e.g. in the same form they lay in my DB.) is:
$rows = search($rows);
if (count($rows) > 0) {
foreach($rows as $row => $texts) {
foreach ($texts as $idea) {
echo $idea;
}
}
}
However, the only thing this code echoes is a long string of all the info that exists in my DB.
The function, which result I'm calling looks like this:
function search($query) {
$query = mysql_real_escape_string(preg_replace("[^A-Za-zÅÄÖåäö0-9 -_.]", "", $query));
$sql = "SELECT * FROM `text` WHERE categories LIKE '%$query%'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows['text'] = $row;
}
mysql_free_result($result);
return $rows;
}
How can I make it echo the actual text that should be the value of the array?
This line: echo $rows['categories'] = $row; in your search function is problematic. For every pass in your while loop, you are storing all rows with the same key. The effect is only successfully storing the last row from your returned query.
You should change this...
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
echo $rows['categories'] = $row;
}
mysql_free_result($result);
return $rows;
to this...
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
return $rows;
Then when you are accessing the returned value, you could handle it like the following...
foreach ($rows as $key => $array) {
echo $array['columnName'];
// or
foreach ($array as $column => $value) {
echo $column; // column name
echo $value; // stored value
}
}
The problem is that you have a multi-dimensional array, that is each element of your array is another array.
Instead of
echo $row['categories'];
try print_r:
print_r($row['categories']);
This will technically do what you ask, but more importantly, it will help you understand the structure of your sub-arrays, so you can print the specific indices you want instead of dumping the entire array to the screen.
What does a var_dump($rows) look like? Sounds like it's a multidimensional array. You may need to have two (or more) loops:
foreach($rows as $row => $categories) {
foreach($categories as $category) {
echo $category;
}
}
I think this should work:
foreach ($rows as $row => $categories) {
echo $categories;
}
If this will output a sequence of Array's again, try to see what in it:
foreach ($rows as $row => $categories) {
print_r($categories);
}

Categories