I have some results from a web form.
I'm working with WP and I get a lot of term_id (from different taxonomy).
In the frontend the form is "dynamic" for each kind of taxonomy (and i dont know before how many they are), I made a multiselect (all select have same NAME ex: terms[] ).
When I process the term_IDs after form Submit I check each term_Id and put it in the right array. EX:
$option = isset($_POST['terms']) ? $_POST['terms'] : false;
if ($option) {
$sql = "SELECT term_id,taxonomy FROM wp_term_taxonomy WHERE term_id IN (".implode(',',$option).") ";
$term_tax = $wpdb->get_results($sql);//print_r($option); exit();
foreach ($term_tax as $tt)
{
$global[$tt->taxonomy][] = $tt->term_id;
}
So in the end I have an array with 1 or N arrays.
For each sub-array i have to do a nested cycle
EX: after process terms i have $gloabl[category] and $global[tag] I need to do
foreach($global[category] as $t)
{
foreach($global[tag] as $x)
{
//do query with $t and $x
}
}
I need to do a query with all combinations of term_ids for each subarray dynamically.
Related
Searched, Googled already couldn't found one with same case,
Basically i have a set of multiple categories in one form, i want to update Number of questions in each category on one form submit.
Following is the form:
Number of categories can be dynamic, each Question TextBox contains its name = "question" merged with category ID and make it as "question12 , question13" etc.
I know about update_batch() , but how do i get values and put them in array as they can be of unknown number.
How do i update all categories at once in CodeIgniter
$post = $this->input->post();
foreach($post as $key=>$value){
if(strpos($key, "question") == 0){
$category_id = substr($key, 8);
//Use $category_id and $value in this loop to build update statement
}
}
I have resolved this using foreach in Controller
foreach ($sample_settings as $sample) {
$array['category_id'] = $sample['category_id'];
$array['no_of_questions'] = $this->input->post('question'.$sample['category_id']);
$batch_array[] = $array;
}
I'm trying to build my own dynamic filtering for my Angular App and Laravel 5.1 API using $httpParamSerializer(params); and Laravel whereIns.
My goal is to pass a set of fields and values I want to filter on and drill down the records I need.
I loop through the fields in Laravel and perform whereIns, then group them into an array, removing duplicates. Unfortunately, this acts more as an OR than an AND, as each whereIn does a new search to match.
Frontend Query:
var filters = {
'review[]' : ['no', 'yes'],
'user_id[]' : [1]
};
HTTP URL: "http://dde-api.localhost/1.0/userquestions?review%5B%5D=no&review%5B%5D=yes&user_id%5B%5D=1"
DB:
Laravel:
$results = [];
// Loop through each field (`review`, `users`, etc..), then search thru array of params
foreach ($input as $filter_field => $filters_array) {
if ($this->validField($table, $filter_field)) {
$res = DB::table($table)->whereIn($filter_field, $filters_array)->get();
if (!in_array($res, $results)) {
array_push($results, $res);
}
I need the query to work as a multiple WHERE clause (AND, not OR) which loops through and appends where clauses to each field ($filter_field), then searches for matching field values.
So the result should be all yes and no records for user 1. Since user 1 doesn't have a record with review: yes, it uses the record from user_id: 4. This is bad.
How can I append multiple WHERE statements to one query as I loop through multiple fields?
Use Your loop like this
$dbTbOBJ = \DB::table("table_name")
// Loop through each field (`review`, `users`, etc..), then search thru array of params
foreach ($input as $filter_field => $filters_array) {
$dbTbOBJ->whereIn($filter_field, $filters_array);
}
$results = $dbTbOBJ->get()
I am pulling my hair out here, I simply cannot get this to work.
I need to do a foreach loop to get all authors in a website, I then need to filter the ones with 0 published articles out and then echo the authors with articles into a UL LI with a special tag for the last author in the array:
My code at the moment has two functions, one to prefilter all authors that have at least one article and then in the second function count the number of authors left in the filtered array to then give the last entry in the array a special li tag. Code so far:
/*********************
Echo Filtered List
*********************/
function filtered_list() {
$authors = get_users('orderby=nicename');
$all_authors = array();
if ( count_user_posts( $author->id ) >= 1 ) {
return true;
}
}
function contributors() {
$i = 0;
filtered_list();
$len = count($all_authors);
foreach ($all_authors as $author ) {
if ( count_user_posts( $author->id ) >= 1 ) {
if ($i == $len - 1) {
echo "<li class='author-last clearfix'>";}
else {
echo "<li class='author clearfix'>";}
$i++;
If you read through your code you would probably see why it doesn't work.
First: Scopes
Read about variable scopes in the PHP manual. Basically, a variable declared inside a function is only available inside that function, so $all_authors is null inside contributors() as it has never been initialized.
The filtered_list function should return a filtered list of authors, so you should loop, though $authors and add the author to $all_authors if, and only if she has 1 or more posts. After the loop, return the array.
Now you can get the filtered list by setting the return value of the fist function to the $all_authors in contributors (or better yet, just call them $authors).
Now you are ready to iterate over the list of authors and find their post. To do this, you need two loops. One for authors, and one for the posts.
foreach author in authors
foreach post in author->posts
if post is last post
print special stuff
else
print normal stuff
endif
endforeach
endforeach
Hope this helps, and that you'll learn something from it. Point is: Read though your code line by line and explain to yourself what it does.
I have a taxonomy vocabulary kategorie like this:
Kat01
Child01
Child02
Kat02
Child01
Child02
The vocabulary has a custom field with IDs like this: 957214d2-ce39-423d-aeb1-32f2e8b972f6, so every term and parent term has an ID (which is NOT the tid!).
I have a content type with a referenced taxonomy field kategorie. Also there is an array field called kategorieTempId, and the values are the same like in the kategorie-taxonomy. The number of IDs in that array represent the hierarchical order of the terms and parent terms. So, if the node should be in kategorie -Kat01 -> Child01, there would be two IDs in kategorieTempId, one for the parent, one for the child term.
Now I need to get the ID of the child term, than get the taxonomy term from the vocabulary and write it into the referenced term field.
What I did so far:
Set up a rule, which is fired before saving a node, using the action Fetch entity by property to get the taxonomy terms from the vocabulary into an array. Then I add an action Execute custom PHP code to find the child tid and write it into a field called katReturn.
Here is the codeI use (I'm a total php-beginner, and I don't know, if this is an elegant way to do it, but it works):
$anzahl = 0; //counter for hierarchy
foreach ($kat_id_fetched as $kat_term) { // fill two arrays
$tid[$anzahl] = $kat_term->tid; // array with termID
$parentTerm_id[$anzahl] = db_query("SELECT {parent} FROM {taxonomy_term_hierarchy} WHERE tid = $kat_term->tid")->fetchField(); // array with parent-termID
++$anzahl;
};
foreach ($tid as $item) { // check if tid is parent
$anzahl = 0;
if (!in_array($item, $parentTerm_id)) {
$kat_child = $item; // if not in parent-array, save tid
$node->field_kat_return['und'][0]['value'] = $item;
break;
};
++$anzahl;
};
So now I know the tid of the child term and I want to write it into the reference taxonomy field, but I don't get it. The code I try is:
foreach ($kat_id_fetched as $kat) {
if ($kat->tid == $returned_kat) {
$node->field_kategorie[] = $kat;
break;
};
};
I hope, I made clear what I want. As I said before, my php-skills are limited and I appreciate any help, which points me to the right direction. Thanx.
The solution is simpler than I thought. Thanks to #Clive
I can save the term-id, which is stored in $item, directly without going through a third foreach-loop.
$node->field_kat_return['und'][0]['tid'] = $item;
I'm looking for the best way to create a complex navigation element on the fly. I have all of the elements in a database (title, id, parentId) and I want to efficiently take them out of the DB and display them correctly. I also want to collapse all of the navigation elements that aren't active. So if I was browsing through "Sofas" I wouldn't see "Chandeliers" or any of the categories under lighting but I would see "Lighting".
This is what I want the final product to look like:
Furniture
Living Room
Sofas
Chairs
Ottomans
Bedroom
Beds
Nightstands
Lighting
Chandeliers
Floor Lamps
Sconces
Rugs & Textiles
Contemporary
Vintage
My current method is
write one SQL query that pulls down all of the category names, ids, and parent ids
Iterate through the categories and put into a sorted multi-dimensional array with child categories stored under their parents.
Iterate through the new array and add another entry to mark the appropriate categories as open (all categories are closed by default)
iterate through the array and write HTML
I'm trying to to this with as few interations as possible and I'm sure the code I have right now is inefficient. Especially step 2 I iterate through the array several times. There has to be a general solution to this (common?) problem.
Consider adding a new field to your database table: level.
Main-categories will have level 0.
Sub-categories will have level 1.
Sub-sub-categories will have level 2.
etc.
This trick will help you to know which sub-categories to disable without 2nd iteration of the array.
I believe this is the perfect place to generate your html code using recursion.
I used this function a while ago. It is working with a multi-dimensional array (tree)
function buildMenu($menu_array, $is_sub=FALSE) {
$attr = (!$is_sub) ? 'id="menu"' : 'class="submenu"';
$menu = "<ul $attr>\n";
foreach($menu_array as $id => $elements) {
foreach($elements as $key => $val) {
if(is_array($val)) {
$sub = buildMenu($val, TRUE);
}
else {
$sub = NULL;
$$key = $val;
}
}
if(!isset($url)) {
$url = $id;
}
$menu .= "<li>$display$sub</li>\n";
unset($url, $display, $sub);
}
return $menu . "</ul>\n";
}
echo buildMenu($menu_array);
This adds css properties too. If you wish to mark the currently active page you can use the strpos() function to find your current url. If you need some more functionality you can easily add them to buildMenu()
Using level as mentioned in the answer above will help too. If you were using the nested set model in your database I could also help you with my query which is a single select returning the whole menu data.