Trouble creating parent-child relationship between two database tables using php codeigniter - php

I have two databases tables called article_category and article_case. They are supposed to be combined in a webpage as below:
Article category[title]
Article category[description]
Article case[title]
Article case[contents]
Article case[title]
Article case[contents]
This should repeat itself using foreach until all article categories are populated on the page.
Each article_case will also use foreach, but it has to respect its 'category_id' value which matches the 'id' in article_category .
I'm having trouble filtering the article_case table so that it only picks up rows from its parent 'category_id'.
This is my current php code (which only makes an array of each table):
$this->db->select( "id,title,description" );
$this->db->from( 'article_category' );
$query_article_category = $this->db->get_compiled_select();
$query = $this->db->query( $query_sustainability_category . 'ORDER BY sort ASC ' );
foreach ($query->result_array() as $val) {
$data['article_category_posts'][$val['id']] = $val;}
$this->db->select( "id,category_id,title,contents" );
$this->db->from( 'article_case' );
$query_article_case = $this->db->get_compiled_select();
$query = $this->db->query( $query_article_case);
$data[ 'article_cases' ] = $query->result_array();
And here is my html:
<?php foreach ($article_category_posts as $key => $val) { ?>
<section>
<h2><?php echo $val['title']; ?></h2>
<p><?php echo $val['description']; ?></p>
</section>
<?php foreach ($article_cases as $key => $val) { ?>
<section>
<h3><?php echo $val['title']; ?></h3>
<p><?php echo $val['contents']; ?></p>
</section>
<?php } ?>
<?php } ?>
The current setup will input all article_cases disregarding the category_id.
How can I use foreach while assigning each article_case to their respective article_cateogry?

This would generate unnecessary amount of queries to the DB server.
The rly basic approach would be:
select all categories (as you have) SELECT * FORM a_category
for each category select cases SELECT * FROM a_case WHERE category_id = {$category['id']}
The second one is to combine the categories and cases right in the query with join and adjust the resulting data in php:
SELECT cat.title, cat.description, case.id AS case_id, case.category_id, case.title, case.content
FROM a_case case
INNER JOIN a_category cat ON cat.id = case.category_id

You can use a query to get all the records of article_case with related article_category.
group the query result by category_id.
$this->db->select("cat.title,cat.description,case.category_id,
case.title AS case_title, case.contents" );
$this->db->from( 'article_category cat');
$this->db->join('article_case case','case.category_id=cat.id');
$result=$this->db->get()->result_array();
$result_group = array_group_by($result, 'category_id');
array group by function
function array_group_by(array $array, $key)
{
if (!is_string($key) && !is_int($key) && !is_float($key) && !is_callable($key)) {
trigger_error('array_group_by(): The key should be a string, an integer, or a callback', E_USER_ERROR);
return NULL;
}
$func = (is_callable($key) ? $key : NULL);
$_key = $key;
// Load the new array, splitting by the target key
$grouped = [];
foreach ($array as $value) {
if (is_callable($func)) {
$key = call_user_func($func, $value);
} elseif (is_object($value) && isset($value->{$_key})) {
$key = $value->{$_key};
} elseif (isset($value[$_key])) {
$key = $value[$_key];
} else {
continue;
}
$grouped[$key][] = $value;
}
// Recursively build a nested grouping if more parameters are supplied
// Each grouped array value is grouped according to the next sequential key
if (func_num_args() > 2) {
$args = func_get_args();
foreach ($grouped as $key => $value) {
$params = array_merge([$value], array_slice($args, 2, func_num_args()));
$grouped[$key] = call_user_func_array('array_group_by', $params);
}
}
return $grouped;
}
in view you can show as below
<?php foreach ($result_group as $key => $cat_result) { ?>
<section>
<h2><?php echo $cat_result[0]['title']; ?></h2>
<p><?php echo $cat_result[0]['description']; ?></p>
<div class="box-bd-doted">
</section>
<?php foreach ($cat_result as $key => $val) { ?>
<section>
<h3 style="color:red"><?php echo $val['case_title']; ?></h3>
<p><?php echo $val['contents']; ?></p>
</section>
<?php }
}
?>

Related

How to retrieve the value of the field in ACF?

<?php if( $fields )
{
foreach( $fields as $field)
{
$value = get_field( $field['name'] );
if ($value) {
echo '<dl>';
echo '<dt>' . $field['label'] . '</dt>';
echo '<dd>' . $field['value'] . '</dd>';
echo '</dl>';
}
}
}
?>
This is what I have. If I do a var_dump on acf_get_fields, it apparently sets the value to NULL. I could have known, as it's written here:
https://www.advancedcustomfields.com/resources/get_field_object/
The problem: I have to first get all fields in a specific field_group, hence I am using acf_get_fields.
I thought with using $field['value'] I could get it to work, but apparently this does not work.
Can someone help me to retrieve the values in the foreach per field? Surely there must be a way?
PS:
<?php
$fields = get_fields();
if( $fields ): ?>
<ul>
<?php foreach( $fields as $name => $value ): ?>
<li><b><?php echo $name; ?></b> <?php echo $value; ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
This gives me ALL fields. I just need a specific list of fields from a specific field group. That is the problem. Anybody knows how I can solve it?
<?php
$fields = get_field('fieldname');
foreach( $fields as $field)
{
echo '<dl>';
echo '<dd>' . $field . '</dd>';
echo '</dl>';
}
?>
Think the value is always NULL because you're getting it only the group fields, not the fields from a post. Have made a few examples maybe this will help you out.
$post_id = 123;
$group_id = 1234;
// Get post fields
$post_fields = get_fields($post_id);
foreach ($post_fields as $key => $value) {
if ($key == 'my_custom_field') {
echo $value;
}
}
// Get group fields
$group_fields = acf_get_fields($group_id);
foreach ($group_fields as $key => $group_field) {
if ($key == 'my_custom_field') {
echo $value;
}
}
// Get field objects
$field_objects = get_field_objects($post_id);
foreach ($field_objects as $key => $field_object) {
if ($key == 'my_custom_field') {
echo $field_object['value'];
}
if ($field_object['name'] == 'my_custom_field') {
echo $field_object['value'];
}
// only show fields from specific group
if ($field_object['parent'] == $group_id) {
echo $field_object['value'];
}
}

how to add another loop based on the id of the first loop, in codeigniter

I want to display the data of all employees based on places, where data places are looped based on date data, here is the code.
in the model
public function getSchedule()
{
$builder = $this->db->table('tb_dates');
....
$dates = $builder->get()->getResultArray();
foreach ($dates as $key => $value) {
$builder = $this->db->table('tb_places');
$builder->join('tb_dates', 'tb_dates.iddate = tb_places.iddate');
$builder->where('tb_dates.iddate', $value['iddate']);
$result = $builder->get();
$places = $dates[$key]['places'] = $result->getResultArray();
// more looping (this question)
foreach ($places as $key => $value) {
....
}
}
return $dates;
}
and then in controller :
$data['sch'] = json_encode($this->schedule->getSchedule());
return view('admin/index', $data);
in view :
<?php $schedules = json_decode($sch); ?>
<?php foreach ($schedules as $schedule) : ?>
....
<?php foreach ($schedule->places as $key) : ?>
....
**for example, i want an loop for the employee data in here**
.......
<?php endforeach; ?>
<?php endforeach; ?>

Outputting categories authors have written in as a class (WordPress)

OK, I have a very specific question that I hope someone can shed some light on.
I have a page that lists authors outputting using the following code
<?php
$display_admins = false;
$order_by = 'post_count'; // 'nicename', 'email', 'url', 'registered', 'display_name', or 'post_count'
$role = ''; // 'subscriber', 'contributor', 'editor', 'author' - leave blank for 'all'
$hide_empty = true; // hides authors with zero posts
if(!empty($display_admins)) {
$blogusers = get_users('orderby='.$order_by.'&role='.$role);
} else {
$admins = get_users('role=administrator');
$exclude = array();
foreach($admins as $ad) {
$exclude[] = $ad->ID;
}
$exclude = implode(',', $exclude);
$blogusers = get_users('exclude='.$exclude.'&orderby='.$order_by.'&role='.$role.'&order='.'DESC');
}
$authors = array();
foreach ($blogusers as $bloguser) {
$user = get_userdata($bloguser->ID);
if(!empty($hide_empty)) {
$numposts = count_user_posts($user->ID);
if($numposts < 1) continue;
}
$authors[] = (array) $user;
}
echo '<ul class="contributors">';
foreach($authors as $author) {
$display_name = $author['data']->display_name;
$avatar = get_wp_user_avatar($author['ID'], 'medium');
$author_profile_url = get_author_posts_url($author['ID']);
$filter = get_userdata($author['ID'])->yim;
echo '<li><div class="home ', $filter,' "><div class="feature-image">', $avatar , '</div>
<div class="post-title"><h3>', $display_name, '</h3></div>
</div>
</li>';
}
echo '</ul>';
?>
(I got this from another support topic and tweaked it, although I can't remember where)
At the moment, the $filter variable is just a string I enter in the 'Yahoo IM' profile box (a dirty fix to test the filter). I'd like this to actually be a list of the categories (as slugs that I will output in to the class="" part of the loop) that the author has posted in.
I essentially want to be able to filter the authors by category that they have posted in, and the filter I'm using (Isotope) operates using the class, so outputting the categories in to the class of the markup is what I'm after.
Any suggestions gratefully received!
// Returns the posts made by the author
$authorPosts = get_posts("author={$author['ID']}");
$categoryList = array(); // reset previous values
foreach ($authorPosts as $post) {
$postCategories = get_the_category($post->ID);
// Add to the categories the author has posted in
foreach ($postCategories as $category)
$categoryList[] = $category->slug;
}
// Removes duplicate categories
$categoryList = array_unique($categoryList);
You can then use $filter = implode(' ', $categoryList); and add it to your html.
RE not storing the array from the other answer, you can just echo out the slugs there and then like this:
$authorPosts = get_posts("author={$author['ID']}");
foreach ($authorPosts as $post) {
$postCategories = get_the_category($post->ID);
// Add to the categories the author has posted in
foreach ($postCategories as $category)
echo($category->slug);
}
otherwise if you want to put your PHP at the top and echo out the slugs further down the page pop there where ever you want to echo them:
$i = 0;
foreach($categoryList as $category) {
echo($categoryList[$i]);
$i++;
}

Extracting image value from Array in Codeigniter

I'm having issues extracting a value from an array of images via Codeigniter/MySQL. So i have a table called "image" in my database and if i echo out it i get the following code:
{"f01efdf6fe3b2bb387d3094aa701203f":{"filename":"f01efdf6fe3b2bb387d3094aa701203f.jpg","alt":"","caption":"","primary":true},"b11581adadd1848acb2898e7a284afc1":{"filename":"b11581adadd1848acb2898e7a284afc1.png","alt":"","caption":""},"2cfee6d3c334696833b1cfe13910fcf1":{"filename":"2cfee6d3c334696833b1cfe13910fcf1.png","alt":"","caption":""}}
As you can see there are 3 images there, what i need is to echo out just the image where "primary" value is:true within a foreach loop...
EDIT:
<?php
$query = $this->db->query("SELECT * FROM offers_products WHERE offer_large LIMIT 5;");
?>
<?php foreach ($query->result() as $row): ?>
<li><?=$row->id?></li>
<li><?=$row->name?></li>
<li><!-- THIS IS THE IMAGES TABLE VALUE --> <?=$row->images?> <!-- --></li>
<li><?=$row->description?></li>
<?php endforeach; ?>
Maybe:
$array = json_decode($stringFromDatabase, true);
$primary = false;
foreach ($array as $longStringDontCare => $imageArray) {
if (!empty($imageArray['primary'])) {
$primary = $imageArray;
break;
}
}
if ($primary) {
echo $primary['filename'];// should give: f01efdf6fe3b2bb387d3094aa701203f.jpg
}
To give you one last hint:
<?php
function getPrimaryImageFromJsonString($stringFromDatabase) {
$array = json_decode($stringFromDatabase, true);
$primary = false;
foreach ($array as $longStringDontCare => $imageArray) {
if (!empty($imageArray['primary'])) {
$primary = $imageArray;
break;
}
}
if ($primary) {
return $primary['filename'];
}
return null;
}
?>
<?php foreach ($query->result() as $row): ?>
<li><?=$row->id?></li>
<li><?=$row->name?></li>
<li><?php echo getPrimaryImageFromJsonString($row->images);?></li>
<li><?=$row->description?></li>
<?php endforeach; ?>
L.E: a few edits.
You have to first decode the json encoded string and extract the primary image from there:
Here is small function which you can use to extract the primary image:(You can place this function in Helper if you are using CodeIgniter)
function get_primary_image($encode_json_data)
{
$primary_image = '';
$decoded_json = json_decode($encode_json_data);
foreach($decoded_json as $obj)
{
if(isset($obj->primary) && $obj->primary == 1)
$primary_image = $obj->filename;
}
return $primary_image;
}
You can call above function in your view in following way:
<?php foreach ($query->result() as $row): ?>
<li><?=$row->id?></li>
<li><?=$row->name?></li>
<li> <?=get_primary_image($row->images)?></li><!-- Here, you call above function -->
<li><?=$row->description?></li>
<?php endforeach; ?>

How to sort results (by name) of an array?

I am using which code which returns taxonomies which match 2 values.
Everything works as it should, but I can't figure out how to order my results. Right now they are displayed in some set order, it might be date not sure. I am trying to get them to display alphabetically (by name)..
My Code from my php template is pasted here http://pastie.org/5083124
The array I am talking about is this
<?php
foreach ( $all_terms as $all_term) {
//print_r($all_terms);
$tax_test = get_option('woo_categories_panel_taxonomies_'.$all_term->taxonomy);
$post_images = array();
$posts_aray = array();
$parent_id = $all_term->term_taxonomy_id;
$term_name = $all_term->name;
$term_parent = $all_term->parent;
$term_slug = $all_term->slug;
$term_id = $all_term->term_id;
$term_link = get_term_link( $all_term, $all_term->taxonomy );
$counter_value = $all_term->count;
?>
<div class="childListings">
<div class="block">
<a href="<?php echo $term_link; ?>">
<?php
$block_counter++;
?>
</a>
<h2><?php echo $term_name ?> <br/><span>(<?php echo $counter_value; ?> Solicitors)</span></h2>
</div><!-- /.block -->
</div><!-- /.child Listings-->
<?php
if ( $block_counter % 6 == 0 ) {
?>
<div class="fix"></div>
<?php
} // End IF Statement
// End IF Statement
?>
<?php
} // End For Loop
?>
I have looked at a few different options with $args and ksort, but I get a bit lost and can't seem to get my results on the frontend of the site to be sorted alphabetically.
Can anyone identify in my code how I would be able to have my results have a sort order?
Thanks
You can avoid bothering to sort in the PHP by sorting slightly earlier, when you're querying the database. This should be faster.
Change:
$all_terms = $wpdb->get_results("SELECT * FROM ipt1y7_term_taxonomy,ipt1y7_terms WHERE ipt1y7_term_taxonomy.parent='{$ex[2]}' AND ipt1y7_term_taxonomy.term_id=ipt1y7_terms.term_id");
...to:
$all_terms = $wpdb->get_results("SELECT * FROM ipt1y7_term_taxonomy,ipt1y7_terms WHERE ipt1y7_term_taxonomy.parent='{$ex[2]}' AND ipt1y7_term_taxonomy.term_id=ipt1y7_terms.term_id ORDER BY ipt1y7_terms.name");
i.e. just add ORDER BY name to your original query. The results will be returned sorted by name with no need for you to do anything further in the PHP, and the sort will happen on the database server. The WordPress database table terms has an index on the name column, so this should be very fast; effectively the data is pre-sorted for you. (See the description of the terms table in the WP database schema.)
Have a look at the examples in http://php.net/manual/en/function.sort.php
$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
foreach ($fruits as $key => $val) {
echo "fruits[" . $key . "] = " . $val . "\n";
}
The above example will output:
fruits[0] = apple
fruits[1] = banana
fruits[2] = lemon
fruits[3] = orange
This is possible using usort and your own comparison function:
<?php
/**
* For a bit of testing.
*/
$all_terms = array( );
$names = array( 'foo', 'baz', 'bar', 'qux', 'aaa' );
foreach( $names as $name ) {
$tmp = new stdClass();
$tmp->name = $name;
$all_terms[] = $tmp;
}
/**
* Here, we do the sorting:
*/
usort( $all_terms, function( $a, $b ) {
if( $a->name === $b->name ) {
return 0;
}
return ( $a->name < $b->name ) ? -1 : 1;
});
/**
* And the results:
*/
var_dump( $all_terms );

Categories