Codeigniter :Parsing array in view - php

I have 2 array indexes in my data array users and books
this is how i am creating this array in my controller
public function getuserhistory($id){
$query= $this->db->get_where('book_assign', array(
'user_id' => $id,
));
return $query->result();
}
public function booksrecord($id){
$books= $this->db->get_where('books',array('id' => $id));
return $books->result();
}
public function history($id){
$results['user']= $this->usermodel->getuserhistory($id);
foreach ($results as $value) {
foreach ($value as $subvalue) {
$results[]['books']= $this->usermodel->booksrecord($subvalue->id);
}
}
$data['data'] = $results;
$this->load->view('history', $data);
}
following is the array that i get
Array
(
[user] => Array
(
[0] => stdClass Object
(
[id] => 1
[user_id] => 5
[book_id] => 1
[date_issue] => 2016-07-24 00:00:00
[date_return] => 2016-07-25 00:00:00
)
[1] => stdClass Object
(
[id] => 2
[user_id] => 5
[book_id] => 2
[date_issue] => 2016-07-24 00:00:00
[date_return] => 2016-07-25 00:00:00
)
)
[0] => Array
(
[books] => Array
(
[0] => stdClass Object
(
[id] => 1
[title] => PHP Made Easy
[author] => Dietel & Dietel
[serial_no] => 232323
[qty] => 9
[row_no] => 1
[col_no] => 2
[status] => 1
[category_id] => 1
[description] => This is a book about php
)
)
)
[1] => Array
(
[books] => Array
(
[0] => stdClass Object
(
[id] => 2
[title] => C++
[author] => Dietel & Dietel
[serial_no] => 232323
[qty] => 9
[row_no] => 1
[col_no] => 2
[status] => 1
[category_id] => 1
[description] => This is a book about c++
)
)
)
)
This array has one specific user in user index and books assigned to that user in book index, I've to parse this array in a way that can generate one row in a table where i can show each book assigned to a user in a separrate row . Please helpe me to parse this array
this is the format i've to print
<tr>
<th>User id </th>
<th>Book Title </th>
<th>Date Issued</th>
<th> Date Return</th>
<th> Action</th>
</tr>

Your parent level array is inconsistent with it's elements since first element is an interloper - only that one is user data while other elements are each book data. We can assume that sometimes there could be much more books returned. To keep consistency in that manner I would separate those arrays in two arrays which first holds user data and second one holds books array.
$user = array_shift($parent);
$books = $parent;// convinient naming for later use
Now, you can loop users and dedicate appropriate book using book id
if (count($user))
{
foreach($user as $obj)
{
$rows = "<tr><td>$obj->user->id</td>";
foreach($books as $book)
{
if($book->id == $obj->book_id)
{
$rows .= "<td>$book->title</td>";
}
break;
}
$rows .= "<td>$obj->date_issued</td>";
$rows .= "<td>$obj->date_returned</td>";
$rows .= "<td>Action</td></tr>";
}
echo $rows;
}
Check this if works.
Although this (sh|c)ould work, see to return less data from DB and always try to use DRY methodology. Here you have many objects returned (user key from your array) just for different book id needed. It is pretty much expensive approach and you can check how to use concat in DB for book id or similar function.

Related

PHP Nested Array is misaligned

I have a PHP loop that is pushing data into an array that will eventually be used to create a list of select options in my dropdown.
I feel like it is kinda close but I am doing something wrong somewhere.
The array of types needs to be part of the category it is associated with.
// Get the list of behavior types
public function _behavior_types()
{
$cat = $this->global_model->get_behavior_categories();
$typ = $this->global_model->get_behavior_types();
$output = array();
// Loop over our categories
foreach($cat as $c)
{
// Push the category name to an array
$output[] = $c['categoryName'];
// Loop over our types
foreach($typ as $t)
{
// If this type belongs to the category we are currently in, add it to the array
if($t['categoryID'] == $c['categoryID'])
{
array_push($output, $t);
}
}
}
return $output;
}
I have something out of place however and its causing the array to not be set up in the correct way.
Here is the current output:
Array
(
[0] => Negative
[1] => Array
(
[categoryID] => 2
[points] => -3
[typeID] => 4
[typeName] => Bad School Day
)
[2] => Positive
[3] => Array
(
[categoryID] => 1
[points] => 2
[typeID] => 1
[typeName] => Ate Dinner
)
[4] => Array
(
[categoryID] => 1
[points] => 2
[typeID] => 3
[typeName] => Brushed Teeth
)
[5] => Array
(
[categoryID] => 1
[points] => 3
[typeID] => 2
[typeName] => Completed Homework
)
)
Here is my desired output:
Array
(
[0] => Negative
[0] => Array
(
[categoryID] => 2
[points] => -3
[typeID] => 4
[typeName] => Bad School Day
)
[1] => Positive
[0] => Array
(
[categoryID] => 1
[points] => 2
[typeID] => 1
[typeName] => Ate Dinner
)
[1] => Array
(
[categoryID] => 1
[points] => 2
[typeID] => 3
[typeName] => Brushed Teeth
)
[2] => Array
(
[categoryID] => 1
[points] => 3
[typeID] => 2
[typeName] => Completed Homework
)
)
The dropdown in turn will look like:
Negative
Bad day at school
Positive
Ate Dinner
Brushed Teeth
Completed Homework
Your desired output is not really a valid array structure, at least how you have it typed. $output[0] cannot be both a string Negative and an array of options. I suggest making the category the key something like this:
// Get the list of behavior types
public function _behavior_types()
{
$cat = $this->global_model->get_behavior_categories();
$typ = $this->global_model->get_behavior_types();
$output = array();
// Loop over our categories
foreach($cat as $c)
{
// Push the category name to an array
$output[$c['categoryName']] = array();
// Loop over our types
foreach($typ as $t)
{
// If this type belongs to the category we are currently in, add it to the array
if($t['categoryID'] == $c['categoryID'])
{
array_push($output[$c['categoryName']], $t);
}
}
}
return $output;
}

fastest way to get array block based on value contained within the block (not working)

https://gist.github.com/jcranny/9465715
I have this array (example)...
Array
(
[0] => Array
(
[series] => stdClass Object
(
[term_id] => 5
[name] => Moto2 2013
[slug] => moto2-2013
[term_group] => 0
[term_taxonomy_id] => 3
)
[race_number] => 77
[team] => Technomah carXpert
[constructor] => Suter
[machine] => Honda CBR600RR
)
[1] => Array
(
[series] => stdClass Object
(
[term_id] => 6
[name] => Moto2 2014
[slug] => moto2-2014
[term_group] => 0
[term_taxonomy_id] => 3
)
[race_number] => 15
[team] => La Fonte Tascaracing
[constructor] => Suter
[machine] => Honda CBR600RR
)
[2] => Array
(
[series] => stdClass Object
(
[term_id] => 7
[name] => Moto2 2015
[slug] => moto2-2015
[term_group] => 0
[term_taxonomy_id] => 3
)
[race_number] => 15
[team] => Mapfre Aspar Team Moto2
[constructor] => Suter
[machine] => Honda CBR600RR
)
)
Now I would like to be able to get information from each block.
For example I would like to echo this data:
[race_number]
[team]
[constructor]
[machine]
But I want only to echo this data that is relevant to a specific [series]
I have the [series] term_id so this is my key to get the relevant data, but i'm struggling to get my node function work.
This is the function to do this:
function node_modify_riders_array($rider_id)
{
$fields = get_field("rider_series_data", $rider_id);
foreach($fields as $field_key => $field_val)
{
$new_fields[$field_val["series"]] = $field_val;
}
return $new_fields;
}
Then this is how I am get the series specific data based on the series term id.
$rider_series_data = node_modify_riders_array($rider_id);
$series_id = $series[0]->term_id;
$team = $rider_series_data[$series_id]["team"];
$contstructor = $rider_series_data[$series_id]["constructor"];
$machine = $rider_series_data[$series_id]["machine"];
$race_number = $rider_series_data[$series_id]["race_number"];
But some thing is wrong and I can work it out. Can anyone see where I'm going wrong or help me fix it.
Massive thanks in advance, would really appreciate some help.
What the problem is:
My function node_modify_riders_array is returning null, which is causing my $team, $contstructor, $machine, and $race_number too not output anything.
If I echo $series_id on my example, I get 6
Which should pass though my node_modify_riders_array function and display the relevant array values. But it's not outputting anything and I got no errors.
This is my full code so you can see what I am trying to do...
https://gist.github.com/jcranny/9465715
You are using an object as your array key and not the term_id of your series object.
function node_modify_riders_array($rider_id)
{
$fields = get_field("rider_series_data", $rider_id);
foreach($fields as $field_key => $field_val)
{
$new_fields[$field_val["series"]->term_id] = $field_val;
//^^^^^^^^^ <--- add this
}
return $new_fields;
}

Store into a database table as row the query result

query result
Array
(
[0] => stdClass Object
(
[ingredientID] => 2
[code] => Bf
[description] => 1st Class Flour
[volume] => 8268
[price] => 750
[amount_gram] => 0.02980
[status] => Inactive
[uom_id] => 1
[flour] => Yes
)
[1] => stdClass Object
(
[ingredientID] => 3
[code] => Sf
[description] => 3rd Class Flour
[volume] => 18490
[price] => 635
[amount_gram] => 0.02540
[status] => Inactive
[uom_id] => 5
[flour] => Yes
)
..........
I want to store this results into another table as row inventory.
the table will look like this:
ID inventory
1 (the result)
2 (another result)
And after I will query it back again so that I can display the result.
here's what I have done lately.
store:
//getting the result
$inv = $this->db->get_from('table','id'=>'1')->row();
<input type="hidden" name="inventory" value="<?php print_r($inv)?>">
//storing in the new table
$this->db->insert('table2',array('inventory'=>$this->input->post('inventory')));
getting:
$inventory = $this->db->get_where('table2',array('ID'=>'1'))->row_array();
//result
array
(
[ID] => 1
[inventory] =>
array
(
[0] => stdClass Object
(
[ingredientID] => 2
...... and so on
I want to display everything in the array['inventory'] which is an array of objects.
I've done this
foreach($arr['inventory'] as $invent):
echo $invent['ingredientID'];
but there's an error in the foreach part.
error: Invalid argument supplied for foreach()
What should i do?
endforeach;
assuming:
$results = $this->db->get_where('table2',array('ID'=>'1'))->row_array();
you should use this to print it
foreach($results['inventory'] as $inventory)
{
print_r($inventory->ingredientID);
}

PHP dynamic multidimensional array or objects

I'm trying to create a recursive function (or method) that stores a sub-tiered navigation in an array variable or object. Here is what I have:
class Navigation extends Database
{
function build($parent_id = 0)
{
$query = 'SELECT id, name, href, parent_id
FROM navigation
WHERE parent_id = '.$parent_id.'
ORDER BY name';
$results = $db->query($query);
while ($row = $results->fetch_object()) {
$nav[$row->id] = $row;
// echo $row;
$this->build($row->id);
}
return $nav;
}
}
If you comment out the echo $row everything works fine. So what I want it to do in a three tier navigation is this:
Array
(
[1] => stdClass Object
(
[id] => 1
[name] => Home
[href] => home.php
[parent_id] => 0
)
[2] => stdClass Object
(
[id] => 2
[name] => Company
[href] => company.php
[parent_id] => 0
)
[4] => stdClass Object
(
[id] => 4
[name] => Company Vision
[href] => company_vision.php
[parent_id] => 2
)
[5] => stdClass Object
(
[id] => 5
[name] => Company Goals
[href] => company_goals.php
[parent_id] => 2
)
[3] => stdClass Object
(
[id] => 3
[name] => Products
[href] => products.php
[parent_id] => 0
)
[6] => stdClass Object
(
[id] => 6
[name] => Products Shoes
[href] => products_shoes.php
[parent_id] => 3
)
[7] => stdClass Object
(
[id] => 7
[name] => Nike
[href] => products_shoes_nike.php
[parent_id] => 6
)
)
Just as an example, so the array would dynamically do this:
$nav[$row->id] = $row; // Home
$nav[$row->id] = $row; // Company
$nav[2][$row->id] = $row; // Company Vision
$nav[2][$row->id] = $row; // Company Goals
$nav[$row->id] = $row; // Products
$nav[3][$row->id] = $row; // Products Shoes
$nav[3][6][$row->id] = $row; // Products Shoes Nike
Thanks in advance.
Question: How do you make a recursive function/method and store the recursive information in a variable rather than echoing the results?
Issues:
(a) PHP overwrites the variable every time it calls itself recursively
(b) A solution would be dynamically creating an array on the fly, but I don't know if that is possible
I suspect you need the nested sets algorithm http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/

Remove duplicates from multi-dimensional array based on higher points

I'm racking my brains trying to think of a solution. I can find plenty of solutions to remove dupes from a 2d array but I need to remove dupes where a value is lower than the other. Here is the array:
Array
(
[basketball] => Array
(
[0] => stdClass Object
(
[id] => 2
[username] => Beans
[points] => 30
)
[1] => stdClass Object
(
[id] => 314
[username] => slights
[points] => 20
)
[2] => stdClass Object
(
[id] => 123
[username] => gibb54
[points] => 5
)
)
[soccer] => Array
(
[0] => stdClass Object
(
[id] => 2
[username] => Beans
[points] => 95
)
[1] => stdClass Object
(
[id] => 49
[username] => sans
[points] => 65
)
[2] => stdClass Object
(
[id] => 122
[username] => peano
[points] => 50
)
[3] => stdClass Object
(
[id] => 174
[username] => fordb
[points] => 30
)
[4] => stdClass Object
(
[id] => 112
[username] => danc
[points] => 30
)
)
)
As you may see, user ID 2, Beans is the first selection for both basketball and soccer. As they have more points for soccer, I need to remove their entry for basketball to make ID 314, slights the 0 value.
I would need to do this continually until no user be the 0 value for any of the primary array values twice.
I've tried various combinations of foreach solutions but I'm not getting anywhere. I thought a while loop would be more suitable but I don't know what condition to test for.
Any ideas please?!
I would loop through your data and create a dictionary where the keys are the user ids, and the values are the appropriate user objects with the sport appended. Then you can reconstruct your example data array structure by looping through this de-duped array using the sport data to determine where to put each user.
To create the de-duped array, use something like:
$deDupedData = array();
foreach ($data as $sport => $users) {
foreach ($users as $user) {
if (isset($deDupedData[$user->id])) {
if ($user->points > $deDupedData[$user->id]->points) {
$deDupedData[$user->id]->sport = $sport;
$deDupedData[$user->id]->points = $user->points;
}
} else {
$modifiedUser = $user;
$modifiedUser->sport = $sport;
$deDupedData[$user->id] = $modifiedUser;
}
}
}
// Now reconstruct your array...

Categories