Codeigniter recursive get all ids - php

I would like to get all IDs with recursion from 1 table. I managed to echo those variables but when I tried to put it into array I failed. Here is the string version:
public function get_numProducts($cid)
{
$this->db->select('cat_id');
$this->db->from('ci_categories');
$this->db->where('cat_child',$cid);
$q = $this->db->get();
$result = $q->result();
$i=0;
$a="";
foreach($result as $mainCategory)
{
$a .= $mainCategory->cat_id;
$a .= $this->get_numProducts($mainCategory->cat_id);
}
return $a;
}
When calling this function with param "4" I get string output: 89. Which is good. But I would like to have output an array(4,8,9). Thanks for help
EDIT:
2nd version
public function get_numProducts($cid)
{
$this->db->select('cat_id');
$this->db->from('ci_categories');
$this->db->where('cat_child',$cid);
$q = $this->db->get();
$result = $q->row();
$n = $q->num_rows();
if ($n > 0)
{
$array[] = $result->cat_id." ";
$array[] = $this->get_numProducts($result->cat_id);
}
return $array;
}
This version returns array however multidimensional:
array (size=2)
0 => string '8 ' (length=2)
1 =>
array (size=2)
0 => string '9 ' (length=2)
1 => null

You will have to pass the array be reference to each iteration of the function ..
public function get_numProducts($cid, &$array)
..
$array[] = $cid;
if ($n > 0) $this->get_numProducts($result->cat_id, $array);

Related

Valid array gives php Invalid argument supplied for foreach()

I have the following foreach loop that gives me the invalid argument error:
$all_students = $this -> model_accounts -> get_students_on_account($account['account_id']);
foreach ($all_students as $student)
{
...
}
I tried to debug using print_r to check what the $all_students array looks like and I got this as a result:
Array
(
[0] => Array
(
[id] => 00062
[student_name] => Reckless
[student_surname] => Harmse
[acc_id] => 198
[dob] => 07-07-1993
[gender] => Male
[active] => 1
[has_pic] => 1
[avatar] => 106.jpg
[pic_ver] => 1
[student_identity_num] => 9307075052084
)
)
So the array is there and as seen in the print_r details, it is seen as an array.
I have looked at other similar questions and none of them could help.
Thanx in advance
Added:
Model function used to get the students
function get_students_on_account($account_id)
{
$data = '';
$this->db->where('acc_id', $account_id);
$q = $this->db->get('students');
if ($q->num_rows() > 0)
{
foreach ($q->result_array() as $row)
{
$row['dob'] = $this -> change_date_format($row['dob']);
$data[] = $row;
}
}
return $data;
}
In your function get_students_on_account, replace this:
$data = '';
by this:
$data = array();
This is needed to consistently return an array. You don't want to return a string. When it does, the problem that you described will occur.
Try this
$res = $q->result_array();
foreach ($res as &$row)
{
$row['dob'] = $this -> change_date_format($row['dob']);
}
return $res;
Try this
In Controller
$all_students = $this->model_accounts->get_students_on_account($account['account_id']);
if($all_students == false){
echo "Empty result";
}
else{
foreach ($all_students[0] as $student)
{
...
}
}
In Model
function get_students_on_account($account_id)
{
$query = $this->db->query("SELECT * FROM students WHERE acc_id = $account_id");
$result = $query->result_array();
$count = count($result);
if (empty($count)) {
return false;
}
else{
return $result;
}
}

Reading sql table with a single general dynamic function

I am trying to create a function that reads more easy any sql table no matter what number of columns.
class control_panel {
public function read_table($table_name, array $col_names) {
global $db;
$i = 0;
$result = $db->query("SELECT * FROM $table_name");
while($data = $result->fetch_object()) {
$i++;
foreach($col_names as $col_name) {
$cols[] = $data->$col_name;
}
}
var_dump($cols);
$nr_cols = count($cols);
/*for($j = 0; $j <= $nr_cols $j++) {
$cols[$j] =
}*/
}
}
$cp = new control_panel;
$col_names = array('ID', 'NewsTitle', 'NewsDescrption');
$cp->read_table('newss', $col_names);
Table structure:
ID NewsTitle NewsDescrption
1 title description
10 sda sd
Current output of the var_dump is:
array (size=6)
0 => string '1' (length=1)
1 => string 'title' (length=5)
2 => string 'descroierererer' (length=15)
3 => string '10' (length=2)
4 => string 'sda' (length=3)
5 => string 'sd' (length=2)
Expected output is to echo the table rows when I do $cp->read_table('newss', $col_names); in this way:
<tr>
<td>1</td>
<td>title</td>
<td>description</td>
</tr>
<tr>
<td>10</td>
<td>sda</td>
<td>sd</td>
</tr>
UPDATE change firts block of code to this as per David Jones answer.
public function read_table($table_name, array $col_names) {
global $db;
$results = array();
$result = $db->query("SELECT ".implode(',', $col_names)." FROM $table_name");
while($data = $result->fetch_object()) {
$results[] = $data;
}
foreach($results as $result) {
// how do I ouput dinamically here
//echo $result->$col_name...... this would lied to another array
}
}
Try this. You should only select the columns that you pass in rather than the whole table to limit un needed processing.
class control_panel {
public function read_table($table_name, array $col_names) {
global $db;
$results = array();
$result = $db->query("SELECT ".implode(',', $col_names)." FROM $table_name");
while($data = $result->fetch_object()) {
$results[] = $data;
}
return $results;
}
}
$cp = new control_panel;
$col_names = array('ID', 'NewsTitle', 'NewsDescrption');
$results = $cp->read_table('newss', $col_names);
$table = '';
foreach ($results as $item) {
$table .= '<tr>
<td>'.$item->ID.'</td>
<td>'.$item->NewsTitle.'</td>
<td>'.$item->NesDescription.'</td>
</tr>';
}
var_dump($table);
This should return an array of objects. Then you can access each column in a loop to show your table.
UPDATE:
You shouldn't loop through and generate your table inside the method as it is suppose to be generic and reusable. Instead return the results and loop in the controller or main PHP file.

How to make first array value to uppercase

I am trying to make first array value to uppercase.
Code:
$data = $this->positions_model->array_from_post(array('position', 'label'));
$this->positions_model->save($data, $id);
So before save($data, $id) to database I want to convert position value to uppercase. I have tried by this
$data['position'] = strtoupper($data['position']);
but than it is not storing the value in db with uppercase but as it is what user inputs.
Current output of $data:
Array ( [position] => it [label] => Information Technology )
And I want it in uppercase as IT
Added Model Method
public function get_positions_array($id = NULL, $single = FALSE)
{
$this->db->get($this->_table_name);
$positions = parent::get($id, $single);
$array = array();
foreach($positions as $pos){
$array[] = get_object_vars($pos);
}
return $array;
}
Main MY_Model method
public function array_from_post($fields)
{
$data = array();
foreach ($fields as $field) {
$data[$field] = $this->input->post($field);
}
return $data;
}
This should work:
$data = $this->positions_model->array_from_post(array('position', 'label'));
$data['position'] = strtoupper($data['position']);
$this->positions_model->save($data, $id);
If Its not, then $data array have only read attribute.
The array_from_post() method returns an array with the format below:
$data = array(
'position' => 'it',
'label' => 'Information Technology'
);
So, you could make first value of the array to uppercase, by using array_map or array_walk functions as follows:
$data = array_map(function($a) {
static $i = 0;
if ($i === 0) { $i++; return strtoupper($a); }
else return $a;
}, $array);
Note: This only works on PHP 5.3+, for previous versions, use the function name instead.
Here is the array_walk example, which modifies the $data:
array_walk($data, function(&$value, $key) {
static $i = 0;
if ($i == 0) { $i++; $value = strtoupper($value); }
});
Again, if you're using PHP 5.2.x or lower, you could pass the function name instead.

Creating an array from recursive function in codeigniter

I want to create an array using recursion in Codeigniter. my function make_tree() in controller is :
function make_tree($customer_id,$arr = array()){
$ctree = $this->customer_operations->view_customer_tree($customer_id);
foreach($ctree as $v):
echo $customer_id = $v['customer_id'];
array_push($arr, $customer_id);
$this->make_tree($customer_id);
endforeach;
var_dump($arr);
}
But the var_dump($arr) and echo results output like:
1013
array
empty
array
0 => string '13' (length=2)
11
array
empty
array
0 => string '10' (length=2)
1 => string '11' (length=2)
How can I make a single array of all the three outputs, ie an array with elements 13,10,11
you need to send the array with the parameters otherwise a new array is created.
function make_tree($customer_id,$arr = array()){
$ctree = $this->customer_operations->view_customer_tree($customer_id);
foreach($ctree as $v):
echo $customer_id = $v['customer_id'];
array_push($arr, $customer_id);
$this->make_tree($customer_id, $arr);
endforeach;
var_dump($arr);
}
PS: I don't know what you are trying to do exactly, but you probably need to add a stopping condition that is going to return the final array, unless you want to pass it by reference.
UPDATE
Here is one way to do it:
function make_tree($customer_id, &$arr)
{
$ctree = $this->customer_operations->view_customer_tree($customer_id);
foreach($ctree as $v):
$customer_id = $v['customer_id'];
array_push($arr, $customer_id);
$this->make_tree($customer_id, $arr);
endforeach;
}
and this is how you'd use it:
$final_array = array();
make_tree($some_customer_id, $final_array);
// now the $final_array is populated with the tree data
You can use class scope.
class TheController {
private $arr = array();
function make_tree($customer_id){
$ctree = $this->customer_operations->view_customer_tree($customer_id);
foreach($ctree as $v) {
$customer_id = $v['customer_id'];
array_push($this->arr, $customer_id);
$this->make_tree($customer_id);
}
}
}

retrning an associative array from mysqli statement result

I have the following code.
public function fetch_questions($count=null)
{
$stmt = $this->mysqli->prepare("SELECT question,question_title FROM questions order by id");
$stmt->execute();
$stmt->bind_result($question,$question_title);
$arr = array();
while ($stmt->fetch()) {
$arr = array('question_title'=>$question_title,'question'=>$question);
}
$stmt->close();
return $arr;
}
The output only contents one row, the last row. how can retrieve all records?
$questions = $db->fetch_questions();
var_dump($questions);
Output of var_dump:
array
'question_title' => string 'aaaaaa' (length=6)
'question' => string 'aaaaaaaaaaaaaaaaaaaa' (length=20)
You need to append onto $arr via [], not assign its value directly. Otherwise you are overwriting it on each loop iteration.
while ($stmt->fetch()) {
$arr[] = array('question_title'=>$question_title,'question'=>$question);
//-^^^^
}

Categories