Manipulating Results Array for Multiselect—CodeIgniter - php

I'm trying to populate a multiselect in my view with the results from a query to the database. Sorry if this is a very basic question—I'm a bit new to CodeIgniter and MVC.
My model simply gets all records from a table:
function getAll() {
$query = $this->db->get('example');
return $query->result_array();
}
I then hope to pass the results to my view to populate a multiselect form element. However, the associative array that is returned does not provide the results I'd like.
What I get:
[0] Array
(
[id] => 6
[name] => Bob
What I'd like to get:
[0] Array
(
[6] => Bob
[7] => Linda
Am I missing something with my query that would achieve my desired results? Should I just use a foreach to create a new array that will be formatted the way I would like? If so would this foreach belong in my controller or view.
Thank you for your help.

Try this:
function getAll()
{
$items = $this->db->get('example')->result_array();
if(empty($items))
return array();
$res = array();
$i = 0;
while($i < count($items))
{
$res[$items[$i]['id']] = $items[$i]['name'];
++$i;
}
return array($res);
}

The most efficient way would be to use active record, because it just gets the data from the column 'name' in your table)
$this->db->select('name')
->from('example');
return $this->db->get()->result();
If you were going to use a foreach loop, if you process the results in the controller you would have to process them again in the view, so you may as well send the entire result array to the view and process them in the view. This is useful if you need to use most of the columns of one particular table in your view.

Related

Can I call the unserialize function in "Select Operation" of Yii2 Active Query

In my database table, the list of winners is stored in a serialized way. I know that after fetching the winners record from the database, I can unserialize the data and make an array of it. But for that, I have to use, "foreach" loop or have to do it manually. And I have successfully done that too.
But a thing came to my mind that is this possible to get the data in an unserialized way during the execution of query. Below is my Yii2 Active Query.
$winners = Winners::find()
->select('winners')
->where(['event_id'=> Yii::$app->session->get('event_id')])
->asArray()
->all();
This query is giving me what I want. Let me show you.
(
[0] => Array
(
[winners] => a:10:{i:0;i:0;i:1;i:4;i:2;i:8;i:3;i:13;i:4;i:15;i:5;i:19;i:6;i:20;i:7;i:23;i:8;i:25;i:9;i:26;}
)
But I want the winners list in unserialized form. And I tried doing the following.
$winners = Winners::find()
->select(serialize('winners'))
->where(['event_id'=> Yii::$app->session->get('event_id')])
->asArray()
->all();
But the above query generates an error. Is there any way to Unserialize the winners list during the query execution and get the winners list in array format
Try this :
$winners = Winners::find()
->select('winners')
->where(['event_id'=> Yii::$app->session->get('event_id')])
->asArray()
->all();
$result = unserialize($winners[0]['winners']);
Now use $result.

add data on a array query result

I have the function below in my model which return an array of data. I want to make another operation on each row and add the result to array of data before to return it.
function get_all_annonce()
{
$this->db->select(" * from annonce");
$this->db->order_by("annonce.DATEDEBUTANNONCE","asc");
$q=$this->db->get();
if($q->num_rows()>0)
{
foreach($q->result() as $row)
{
$data[]=$row;
//I try to add another result
$experience=$this->get_experience($row->NUMUSER);
$data['experience']=$experience;
}
return $data;
}
}
But I have an error when I try to access to $experience or $row->'experience' in my view. How can I fix it ?
The $data variable is defined in the wrong scope. You defined it inside the foreach loop but you try to return it after. Try adding $data = Array(); above the foreach.
In addition to the answer above.
First you have unnecessary assignments, you can do it in one line.
2nd - when you use [] - it will create index automatically and the row will be added as an array to that index. You get a multidimensional array( 0 => result 1, 1 => result 2 etc).
If you want to add the 'experience' key to the result, you cannot add it directly to data.
You get an array that will have keys 0,1,2,3,4 ... 'experience' as last key - each time it is overwritten.
One way would be to use a variable for key (or use for loop instead):
$i = 0;
foreach($q->result() as $row)
{
$data[$i]=$row;
$data[$i]['experience'] = $this->get_experience($row->NUMUSER);
}
If you used only [] for both, it would assign different key for each one every iteration.

PHP Codeigniter Array Calculations

I am having a problem, which I hope someone could help me with.
I am using CodeIgniter to pull results from a database, and I would like to add these results together. I am not much of a PHP developer, so I am not too sure where to start.
This is the function I am using;
function get_warranty($id) {
$this->db->select('warranty');
$this->db->where('sID', $id);
$query = $this->db->get('cars');
return $query->result();
}
This function, returns this;
[warranty] = Array
(
[0] => stdClass Object
(
[warranty] => 2
)
[1] => stdClass Object
(
[warranty] => 5000
)
)
But, I would like it to return this;
[warranty] = 5002;
So, it simply adds up each result it finds.
Any help at all, would be greatly appreciated, as I say, I'm not much of a PHP developer, so I don't even know where to start.
Thanks in advance!
The $query -> result() function returns an array of objects with query results...
See documentation: http://ellislab.com/codeigniter/user-guide/database/active_record.html#select
This is the modified function I propose, which simply returns an integer with the total sum, as you need:
function get_warranty($id) {
// Query composition
$this->db->select('warranty');
$this->db->where('sID', $id);
$query = $this->db->get('cars');
// Iterate through the returned objects and accumulation in $warranty
foreach ($query->result() as $row) {
$warranty += $row->warranty;
}
return $warranty;
}
Kind regards.
In place of return $query->result(); use return $query->result_array();. You will get returned with pure array.
Now you can use foreach loop to add the values up like this:
$add_up = 0;
foreach ($reulst_array as $values)
{
$addup = $add_up + $values;
}
This way variable $add_up will contain the added array.

Laravel: Filtering in eloquent with optional user input

I have a list of news stories in my laravel website. On the /news/ page a quick list of stories is shown.
Now I want to allow users to filter news. For example, only show "sports" stories.
In my controller I did this:
$input = Input::all();
$events = DB::table('news')
->where('category', '=', $input['type'])
->order_by('created_at', 'desc')
->paginate(10);
Now, this allows me to visit /news?type=sports and it correctly only shows news items within the sports category. This only works if a type is given though, and will obviously fail if there is no type given.
What is the best solution to this? I know I can check to see if $input['type'] exists, and if it does, write a completely new, second "$news = DB::table('news')..." code, but I am thinking that I may actually want to have multiple user inputs, which would make that option not work. For example, what if I want to sort by type and location? Something like /news?type=sports&area=chicago -- what would I do then?
I know I must be missing something obvious here. Can anyone point me in the right direction?
I think you can do it using a foreach loop, for example
$input = Input::all();
So, you'll get something like this (you should check $input is not null)
Array
(
[type] => sports
[area] => chicago
)
Now, select the table like
$events = DB::table('news');
Now loop the $input like (for multiple dynamic where clause)
foreach ($input as $key => $value) {
$events->where($key, $value);
}
$result = $users->get();
Or you can use orderBy like (for multiple dynamic orderBy clause)
$events = DB::table('news')->where('category', $input['type']);
foreach ($input as $key => $value) {
$events->orderBy($key); // also, you can use ASC/DESC as second argument
}
$result = $users->get();
or you can use
$result = $users->paginate(10);

Display categories in Codeigniter / PHP

I am trying to display categories stored in my database:
http://dl.dropbox.com/u/16459516/Screen%20shot%202012-05-05%20at%2015.59.40.png
My idea was to get all data out of the database within my model and the reconstruct the array within my function:
function get_all_categories() {
$query = $this->db->query('SELECT * FROM categories');
//code to reconstruct my array like:
//foreach($query->result_array() as $row) {
//$categories[$row['niveau_1']] = array[]
//}
return $categories;
}
and output some array like:
[0] => Array
(
[niveau_1] => main category name
[niveau_2] => Array(
...children here and children of these childs
)
)
Does anyone know how to do this? Im stuck here and dont know how to create the array... i know how to display it in my views but getting them in the array seems hard for me.
Thanks in advance!
This is an idea:
foreach category (except level 4) check if it is present into the result array($c)
if it is not then create an array using a label the category's name
once controlle categories 2 and 3 you can insert the last one inside the generated array
$query = $this->db->query('SELECT * FROM categories');
$raw_categories = $query->result_array();
$c = array();
foreach($raw_categories AS $row)
{
if(!array_key_exists($row['niveau_2'],$c) && !empty($row['niveau_2']))
{
$c[$row['niveau_2']] = array();
}
if(!array_key_exists($row['niveau_3'],$c[$row['niveau_2']]) &&
!empty($row['niveau_3']))
{
$c[$row['niveau_2']]['niveau_3'] = array();
}
$c[$row['niveau_2']]['niveau_3'][] = $row['niveau_4'];
}
this is not tested but you can use it as an idea
I think your database is wrong. As I understand it's a "table of content" or similar (category, sub-category, sub-sub-category, etc.). "1. Visie, Beleid..." appears many-many times.
If I'd do I change the database:
table niveau_1
id_1 - primary key
title - string
table niveau_2
id_2 - primary key
id_1 - connect to niveau_1 (which niveau_1 is its 'parent')
title - string
table niveau_3
id_3 - primary key
id_2 - connect to niveau_2 (which niveau_2 is its parent)
title - string
In this case in your database will not duplicated elements and I think your desired query will be simplier:
SELECT
niveau_1.title AS title_1,
GROUP_CONCAT(niveau_2.title,"#") AS title_2,
GROUP_CONCAT(niveau_3.title,"#") AS title_3
FROM niveau_1
LEFT JOIN niveau_2 ON niveau_2.id_1=niveau_1.id_1
LEFT JOIN niveau_3 ON niveau_3.id_2=niveau_2.id_2
GROUP BY niveau_2.id_2
This query is only a half-solution, it isn't perfect for you but you can start from here.
// your model using activerecord
public function getCategories(){
$q = $this->db->get('categories');
if($q->num_rows > 0){
return $q->result();
}else{
return false;
}
}
//your controller
$this->load->model('category_model');
$data['results'] = $this->category_model->getCategories();
foreach($data['results'] as $c){
//iterate through categories, match them to points.
//match category_id in results with category_id in the other table results
//setup a multi dimensional array to build up what you need.
}

Categories