How to through multidimensional array in Codeigniter? - php

I'm trying to get my head around grabbing all variable I need in Codeigniter and then passing those values to the view.
I understand the concept, but am getting stuck on iterating through an array and adding on another array to each of its keys.
The $data['items'] array contains data passed from a model via the get_all() function. The query is basically "Select * from items".
Each item has multiple features and pictures. In order to get the appropriate values I need the id of an item. I can grab this from the first array ($data['items']) which I can then pass to a model function.
I keep getting various errors when trying to do this via the code below. I've tried defining the features and pictures arrays before the foreach loop - still get errors.
I'm sure my syntax is just wrong. Any help is welcome.
$data['items'] = $this->amazon->get_all();
foreach ($data['items'] as $data )
$id = $data->id;
$data['features'] = $this->amazon->get_features($id);
$data['pictures'] = $this->amazon->get_pictures($id);
}
Edit
Based on feedback I've updated the code to this (lines 24 - 30 of the code):
$items = $this->amazon->get_all();
for($i=0; $i<count($items);$i++) {
$data = $items[$i];
$id = $data->id;
$items[$i]['features'] = $this->amazon->get_features($id);
$items[$i]['pictures'] = $this->amazon->get_pictures($id);
}
PHP is complaining with this:
PHP Fatal error: Cannot use object of type stdClass as array in /var/www/ci/application/controllers/main.php on line 28
Here are the functions from the amazon model:
function get_all()
{
$query = $this->db->get('items');
return $query->result();
}
function get_pictures($id) {
$query = $this->db->query("SELECT link FROM pictures WHERE item_id='$id' AND type IN('thumb_set')");
$style = "border-style:solid; border-width:1px";
$class = "modal-thumb";
$results = '';
foreach ($query->result() as $row) {
$results .= "<li style='$style' class='$class'><img src='$row->link' alt=''/></li>";
}
return $results;
}
function get_features($id) {
$query = $this->db->query("SELECT content FROM features WHERE item_id='$id' ORDER BY feature_num DESC");
$results = '';
foreach ($query->result() as $row) {
$results .= "<li>";
$results .= $row->content;
$results .= "</li>";
}
return $results;
}
I'm thinking i need to use 'results_array()' instead of 'results()'? Are my results returned as an object instead of an array the way things are now?

As you said, you have syntax error in the foreach statement, you are redefining the $data array.
foreach ($data['items'] as $data )
Try this:
$items = $this->amazon->get_all();
for($i=0; $i<count($items);$i++){
$data = $items[$i];
$id = $data->id;
$items[$i]['features'] = $this->amazon->get_features($id);
$items[$i]['pictures'] = $this->amazon->get_pictures($id);
}

Related

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;
}

Navigate an array from controller in Codeigniter

Good I'm starting with php and codeigniter, I have the following problem I'm running an array from my model, which is the result of a query, how can I read one by one my records in the controller?
function getCustomers() {
$sql = "SELECT * FROM customers";
$query = $this->db->query($sql);
if ($query->num_rows() > 0) {
$i = 0;
foreach($query->result() as $row) {
$img[$i]['id'] = $row->id;
$img[$i]['name'] = $row->name;
$img[$i]['Location'] = $row->Location;
$img[$i]['telephone'] = $row->telephone;
$i++;
}
return $img;
}
}
You can return array to the controller by loading the model into the controller like this.
$this->load->model('yourmodel');
$array = $this->yourmodel->yourmodelsmethod();
First you have to return this array to your controller like
$this->load->model('yourmodel');
$array['test'] = $this->yourmodel->yourmodelsmethod();
foreach($test as $key=>$value)
{
echo $value;
}
By doing this you can easily print your data from model in controller

Pass array in the CodeIgniter query

I want to pass an array in codeigniter query. Below is my code.
Controller
foreach($array as $values) {
$array_values = $values['download_subcategory_name'];
}
$this->data['get_downloads_content'] = $this->my_model->get_downloads_content($array_values );
Model
public function get_downloads_content($array_values ){
$this->db->select('*');
$this->db->from('my_table');
$this->db->where_in('download_subcategory_name', $array_values );
$this->db->order_by('download_id', 'ASC');
$query = $this->db->get();
return $query->result();
}
My problem is query showing results for only last value of array instead of all array values.
Please help.
Just need little changes within foreach
$array_values = array();
foreach($array as $values) {
$array_values[] = $values['download_subcategory_name'];
^^^
}
OR
$array_values = array();
foreach($array as $key => $values) {
$array_values[$key] = $values['download_subcategory_name'];
^^^^^^
}
Within your code it's storing only the last value from the foreach loop thats why it only gets the single value stored within it.

PHP Array not being delivered

I have some data in a database column called "gcmregid".
I access this data by calling:
public function getAllUsers() {
$r = mysql_query("select * FROM table");
while ($row = mysql_fetch_array($r)) {
$result = array(
'gcmregid' => $row["gcmregid"]
);
}
return $result;
}
Correct me if I'm wrong, but this should deliver an array, due to result = array?
I took this logic from here: Getting Resource id #3 Error in MySql
.Then I thaught using a loop would be helpful, such as:
$userCount = $db->getUserCount(); // counting said table
$registation_ids = array(); // again create array
for($i=0; $i < $userCount; $i++)
{
$gcmRegId = $db->getGCMRegID($selUsers[$i]);
$row = mysql_fetch_assoc($gcmRegId);
//Add RegIds retrieved from DB to $registration_ids
array_push($registation_ids, $row['gcmregid']); // this creates an array consisting of gcmregid s ?
}
It doesn't work either.
Any input would be really appreciated right now...
Thanks
I'm not sure what's going wrong, but if the problem is that it's returning a single item: that's because you keep making a new array with every iteration, discarding the old one. If you want to collect all the rows, make a new array outside of the loop and then add the results to it:
public function getAllUsers() {
$r = mysql_query("select * FROM table");
$result = array();
while ($row = mysql_fetch_array($r)) {
$result[] = array (
'gcmregid' => $row["gcmregid"]
);
}
return $result;
}
You should consider working more on how you name your functions. If you are trying to get gcmregid, the method should not say getAllUsers. Anyway, did you try the following:
public function get_gcmregid() {
$query_result = mysql_query("select * FROM table");
$row = mysql_fetch_array($query_result);
return $result[0]['gcmregid'];
}
OR if you are trying to get all gcmregid in one shot:
public function get_gcmregid() {
$query_result = mysql_query("select * FROM table");
$i=0;
while ($row = mysql_fetch_array($query_result)){
$result[$i++] = $row['gcmregid'];
}
return $result;
}

Translating a database to JSON

I have a method of creating JSON into an array that looks like this:
[{"date":"","name":"","image":"","genre":"","info":"","videocode":""},{...},{...}]
I first tried getting the data from a html page (not the database) like this:
$arr = array();
$info = linkExtractor($html);
$dates = linkExtractor2($html);
$names = linkExtractor3($html);
$images = linkExtractor4($html);
$genres = linkExtractor5($html);
$videocode = linkExtractor6($html);
for ($i=0; $i<count($images); $i++) {
$arr[] = array("date" => $dates[$i], "name" => $names[$i], "image" => $images[$i], "genre" => $genres[$i], "info" => $info[$i], "videocode" => $videocode[$i]);
}
echo json_encode($arr);
Where each linkExtractor looks a bit like this - where it grabs all the text within a class videocode.
function linkExtractor6($html){
$doc = new DOMDocument();
$last = libxml_use_internal_errors(TRUE);
$doc->loadHTML($html);
libxml_use_internal_errors($last);
$xp = new DOMXPath($doc);
$result = array();
foreach ($xp->query("//*[contains(concat(' ', normalize-space(#class), ' '), ' videocode ')]") as $node)
$result[] = trim($node->textContent); // Just push the result here, don't assign it to a key (as that's why you're overwriting)
// Now return the array, rather than extracting keys from it
return $result;
}
I now want to do this instead with a database.
So I have tried to replace each linkExtractor with this - and obviously the connection:
function linkExtractor6($html){
$genre = mysqli_query($con,"SELECT genre
FROM entries
ORDER BY date DESC");
foreach ($genre as $node)
$result[] = $node;
return $result;
}
But I am getting the error:
Invalid argument supplied for foreach()
Avoid redundancy and run a single SELECT
function create_json_db($con){
$result = mysqli_query($con,"SELECT date, name, image, genre, info, videocode
FROM entries
ORDER BY date DESC");
$items= array();
while ($row = mysqli_fetch_assoc($result)) {
$items[] = $row;
}
return $items ;
}
Try to use this. More info in the official PHP documentation:
function linkExtractor6($html){
$result = mysqli_query($con,"SELECT genre
FROM entries
ORDER BY date DESC");
$items = array();
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$items[] = $row;
}
return $items;
}
First, you are not iterating through your results via something like mysqli_fetch_array. So here is the function with mysqli_fetch_array in place. But there is a much larger issue. Read on.
function linkExtractor6($html){
$result = mysqli_query($con,"SELECT genre
FROM entries
ORDER BY date DESC");
$ret = array();
while ($row = mysqli_fetch_array($result)) {
$items[] = $row;
}
return $ret ;
}
Okay, with that done, it still won’t work. Why? Look at your function. Specifically this line:
$result = mysqli_query($con,"SELECT genre
But where is $con coming from? Without a database connection mysqli_query will not work at all. So if you somehow have $con set outside your function, you need to pass it into your function like this:
function linkExtractor6($con, $html){
So your full function would be:
function linkExtractor6($con, $html){
$result = mysqli_query($con,"SELECT genre
FROM entries
ORDER BY date DESC");
$ret = array();
while ($row = mysqli_fetch_array($result)) {
$items[] = $row;
}
return $ret ;
}
Remember, functions are self-contained & isolated from whatever happens outside of them unless you explicitly pass data into them.

Categories