Node id from tid - drupal-7

How to get the nid from tid, so I can used node_load function then used Field_get_items to fetch particular fields. I used taxonomy_select_node() first but it gives me nids of all nodes related to that tid but I want nids of a particular bundle(content type) so I can display contents only for that content type. Now I am using Entityfieldquery, here is my code:
if(isset($_GET['tid'])){
$id=($_GET['tid']);
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');
$query->entityCondition('bundle', 'escorts_product');
$query->propertyCondition('status', 1);
$query->fieldCondition('field_description', NULL, $id, '=');
$result = $query->execute();
print "<pre>";print_r($result);
Here I want to get my field_description from my content type escorts_product for a specific $id=tid but it gives array structure for all tids rather than for a specific one I mentioned in argument?

$query->fieldCondition('field_description', NULL, $id, '='); line should be replaced like this and it will work, $query->fieldCondition('field_your_term_reference_field', tid, $id, '='); then you can get the nid easily.

This works for me
$termid = array(1); //Where you save term ID(s)
$nids = taxonomy_select_nodes($termid);
$products = array(); //Lets say nodes type is PRODUCT
if (!empty($nids)) {
foreach ($nids as $nid => $value) {
echo $products[$value] = node_load($value)->title; // Echo all the titles of related nodes of current term.
}
}

Related

Use results from one array in another array

I have a logged in user following other users in a blog. I would like my logged in users to see posts from users they follow.
I run a query that returns a list of user_ids (user_id1) a logged in user (user_id2) follows in an array. I then run the array through a foreach loop to get the list of users as user ids and place it in a new array. The returned user1_ids are echoed as a string. I would now like to use the returned user1_ids in another array that only displays posts based on the user1_ids.
The issue is that the values are returned as a string and my second array used in the posts only reads the first number of the first array as the values are returned as a string and not integers.
How can I use the results from my first array in my second array 'author__in'=> array()? Do I need to convert the string into integers or is there a better method?
// The database query that returns the array
<?php
$currentloggedinuser = get_current_user_id();
$followers_query = $wpdb->get_results("SELECT ID, user_id1 FROM wp_followers WHERE user_id2 = '$currentloggedinuser' ") ?>
// the returned array from the query through foreach placed in another array
<?php
$following_id = array();
foreach ($followers_query as $follower) {
$following_id[] = $follower->user_id1;
sort($following_id);
$following_ids = implode(", ",$following_id);
}
?>
// the resulting number values returned as a string
<?php echo $following_ids; ?>
<?php
$args = array(
'author__in'=> array($following_ids), // user1_ids I'd like to include from the array above
'post_type' => 'post'
);
This would probably work. I did not test it but it should be fine.
Here is some info on the $wpdb::get_col method
<?php
$currentloggedinuser = get_current_user_id();
// Get an array containing only the user_id1 values.
// It's a good habit to use the prepare method of $wpdb
// for security and ease of reading the code
// Also, you should use $wpdb->prefix instead of using the 'wp_' for the table name
// that prefix can be changed and your code would break.
$followers = $wpdb->get_col(
$wpdb->prepare(
"SELECT user_id1 FROM {$wpdb->prefix}followers WHERE user_id2 = %d",
$currentloggedinuser
)
);
sort($followers); // or you can just apply sorting in the query above
// Directly echo the imploded array.
// No need to store it in a variable to do so unless you want to use it somewhere else
echo implode(', ', $followers);
$args = array(
'author__in'=> $followers, //use the array we got from the query
'post_type' => 'post'
);

CakePhp foreach saving only last value in array

I have a problem, right now Im using this foreach loop on CakePhp on which I want to add all the values which are still not on the table for the respecting user. To give a little more context, the user has a menu. And the admin can select which one to add for the user to use. On the next code I receive a array with the menus which will be added as so:
//This is what comes on the ['UserMenuAccessibility'] array:
Array ( [menu_accessibility_id2] => 2 [menu_accessibility_id3] => 3 [menu_accessibility_id4] => 4 [menu_accessibility_id5] => 5 [menu_accessibility_id8] => 8 )
I get the ids of the menus which want to be added to the table for the user to use. And I use the next code to add the menus to the table if they are not there still:
//I check if the array has something cause it can come with no ids.
if (!(isset($this->request->data['UserMenuAccessibility']))) {
$this->request->data['UserMenuAccessibility'] = array();
}
$UserMenuAccessibility = $this->request->data['UserMenuAccessibility'];
foreach ($UserMenuAccessibility as $key => $value) {
$conditions = array(
'UserMenuAccessibility.menu_accessibility_id' => $value,
'UserMenuAccessibility.users_id' => $id
);
if ($this->User->UserMenuAccessibility->hasAny($conditions)) {
} else {
$valuemenu['UserMenuAccessibility']['users_id'] = $id;
$valuemenu['UserMenuAccessibility']['menu_accessibility_id'] = $value;
if ($this->User->UserMenuAccessibility->save($valuemenu)) {
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
For some reason the array is only saving the last new id which is not on the table and not the rest. For example if I have menu 1 and 2 and add 3 and 4 only 4 gets added to the table. For some reason I cant add all the missing menu ids to the table. Any ideas why this is happening?
Thanks for the help on advance.
It looks like your code will save each item, but each call to save() is overwriting the last entry added as $this->User->UserMenuAccessibility->id is set after the first save and will be used for subsequent saves. Try calling $this->User->UserMenuAccessibility->create() before each save to ensure that the model data is reset and ready to accept new data:-
$valuemenu['UserMenuAccessibility']['users_id'] = $id;
$valuemenu['UserMenuAccessibility']['menu_accessibility_id'] = $value;
$this->User->UserMenuAccessibility->create();
if ($this->User->UserMenuAccessibility->save($valuemenu)) {
}
In cakephp 2.0 $this->Model->create() create work fine. But if you are using cakephp version 3 or greater then 3. Then follow the below code
$saveData['itemId'] = 1;
$saveData['qty'] = 2;
$saveData['type'] = '0';
$saveData['status'] = 'active';
$saveData = $this->Model->newEntity($saveData);
$this->Model->save($materialmismatch);
In normal case we use patchEntity
$this->Model->patchEntity($saveData, $this->request->data);
It will only save last values of array so you have to use newEntity() with data
In cakephp3, patchEntity() is normally used. However, when using it for inserting-new/updating entries in a foreach loop, I too saw that it only saves the last element of the array.
What worked for me was using patchEntities(), which as explained in the patchEntity() doc, is used for patching multiple entities at once.
So simplifying and going by the original code sample to handle multiple entities, it could be:
$userMenuAccessibilityObject = TableRegistry::get('UserMenuAccessibility');
foreach ($UserMenuAccessibility as $key => $value) {
$userMenuAccessibility = $userMenuAccessibilityObject->get($value);//get original individual entity if exists
$userMenuAccessibilities[] = $userMenuAccessibility;
$dataToPatch = [
'menu_accessibility_id' => $value,
'users_id' => $id
]//store corresponding entity data in array for patching after foreach
$userMenuAccessibilitiesData[] = $dataToPatch;
}
$userMenuAccessibilities = $userMenuAccessibilityObject->patchEntities($userMenuAccessibilities, $userMenuAccessibilities);
if ($userMenuAccessibilityObject->saveMany($requisitions)) {
} else {
$this->Session->setFlash(__('The users could not be saved. Please, try again.'));
}
Note: I haven't made it handle if entity doesn't exist, create a new one and resume. That can be done with a simple if condition.

What data structure should I use to store a collection of .fasta headers?

I'm trying to write a perl program that will split up a fasta header:
gi|4140243|dbj|AB022087.1|_Xenopus_laevis_mRNA_for_cytochrome_P450,_complete_cds,_clone_MC1
Into it's | seperated parts:
gi
4140243
dbj
AB022087.1
_Xenopus_laevis_mRNA_for_cytochrome_P450,_complete_cds,_clone_MC1
I can do this using split:
my #hits = split(/\|/, $hits);
my ($gi, $number, $gb, $id, $name);
foreach (#hits) {
$gi.= "$hits[0]\n";
$number .= "$hits[1]\n";
$gb .= "$hits[2]\n";
$id .= "$hits[3]\n";
$name .= "$hits[4]\n";
}
my #gi = split('\n', $gi);
my #number = split('\n', $number);
my #gb = split('\n', $gb);
my #id = split('\n', $id);
my #name = split('\n', $name);
Now each part of each header (contained in $hits) is an element in an individual array. What I want to do next is print back each element of each array so that I can produce a list of element[0] for each array, element[1] for each array...
I'm unsure as to whether this will require a hash of hashes or array of arrays.
I'm fairly new to perl so any suggestions would be greatly helpful.
I'm also aware that the above might not be the slickest way of achieving what I want - again any comments would be great!
Does $hits contain one header or many? If it's only one, so to split it into variables you can do something like:
my ($gi, $number, $gb, $id, $name) = split(/\|/, $hits);
And each variable will contain corresponding value.
If $hits contains multiple headers then firstly just split lines and after that split each header in loop. Here is an example and result will be array of hashes:
my #hits = split(/\n/, $hits);
my #result;
for my hit ( #hits ) {
my ($gi, $number, $gb, $id, $name) = split(/\|/, $hits);
push(#result, {
gi => $gi,
number => $number,
gb => $gb,
id => $id,
name => $name,
});
}
Of course the example does not include any error check (such as - does header string really matches the format or not?), but you should include them in a real application if they are needed.
PS: I think you really have to start with that
Generally speaking, arrays are for homogeneous data ("a bunch of things"), while hashes are for heterogeneous data ("a name, a number, and a birthday"). If your data splits naturally into a bunch of internally-heterogeneous things ("a bunch of personal information records, each of which has a name, a number, and a birthday"), the natural data structure is an array of hashrefs (see note#1).
In your case, $hits is a list of headers. So we'll make an array, call it #headers, each element of which is an individual header represented as a hashref. We can turn a delimited string into a list with split, and we can turn one kind of list into another with map:
my #headers = map {
make_header_hashref($_)
} split(/\n/, $hits);
sub make_header_hashref {
my ($header_string) = #_;
my ($gi, $number, $gb, $id, $name) = split(/\|/, $header_string);
return {
gi => $gi,
number => $number,
gb => $gb,
id => $id,
name => $name,
};
}
(I split the conversion of header string to header hashref into a sub because
(a) that's what you'd do in real code and (b) it clarifies the structure of
the map.)
You now have an array of hashrefs, so you can iterate through them and
otherwise deal with the headers as units rather than as collections of
attributes.
note#1: Well, really we would want an object describing the association, implemented as an array of objects that represent the records.

Foreach logic issue with CakePHP

I have I problem that I hope someone can help me with. I thought this code was right, but it will not work. Below is my code, it is a function for my CakePHP 2.2.2 site, the main aim of the code is to produce a menu system from database results. The problem is with my foreach loop, it will not loop. All $Key does is return the value of 2 (three records within the table at this time). So When I display / echo / debug $Menu, the only result I get is the last result stored within the database.
I know the SQL command is right, if that is debuged / echoed then all three results are displayed. The idea of this loop was to get it to count the results, so that I could run a check on a selected field. Where I am going wrong?
function MenuSystem() {
$this->loadModel('Menu');
$MenuSQL = $this->Menu->find('all', array('conditions' => array('active' => true)));
foreach ($MenuSQL as $Key=>$Value) {
$MenuSystem = $MenuSQL[$Key];
$this->Menu = $MenuSystem;
}
}
Many Thanks,
Glenn.
UPDATE :::
Below is my function, now my foreach loop now works, don't know what I was doing wrong, but I know think its working. You can see the print_r command that I am using for testing, if I use that, then all links from my database are printed / echoed on the screen and all works. But if I try and call the $this->Menu from another controller, then only the last record is echoed on the screen. I have moved the $this->Menu outside of the foreach loop, but it made no difference, with it inside the loop or outside, it still only echoes the last record and not all three. So what I am doing wrong?
function MenuSystem() {
$this->loadModel('Menu');
$SiteBase = '/projects/cake/';
$MenuSQL = $this->Menu->find('all', array('conditions' => array('active' => true)));
foreach ($MenuSQL as $key => $Value) {
$MenuAccessLevel = $MenuSQL[$key]['Menu']['roles_id'];
if ($MenuAccessLevel == 1) {
$Path = $MenuSQL[$key]['Menu']['path'];
$Title = $MenuSQL[$key]['Menu']['title'];
$MenuSys = "<a href=\" " . $SiteBase . $Path . " \">" . $Title ."";
} else {
print ("Admin");
}
//print_r($MenuSys);
} //End of Foreach Loop
$this->Menu = $MenuSys;
} //End of function MenuSystem
So When I display / echo / debug $Menu, the only result I get is the last result stored within the database.
You're setting the value of $this->Menu within the foreach, so when the foreach is complete it will take the last value iterated over.
If you want to find the number of records matching a condition, try:
$menuCount = $this->Menu->find('count', array(
'conditions'=>array('active'=>true)
));
$this->set(compact('menuCount'));
Edit: also, by setting the value of $this->Menu within the foreach, you're overwriting the Menu model variable. This is not a good idea.
Edit2: to get the counts of rows as grouped by some value, try:
$this->Menu->virtualFields = array('count' => 'count(*)');
$counts = $this->Menu->find('all', array(
'group'=>'Role',
'fields'=>array('Role', 'count'),
));
This generates SQL to have the results grouped by the Role column. Returned fields are the name of the role, and the number of rows having that value.
If you wanted to do it with a foreach loop instead, it might look like:
$menus = $this->Menu->find('all', array('fields'=>array('id', 'Role')));
$counts = array('user'=>0, 'admin'=>0);
foreach ($menus as $menu) {
$role = $menu['Menu']['Role'];
$counts[$role] += 1;
}

Drupal 7 pull content type fields with db api

What am I doing wrong. I can't seem to pull based upon content type fields in drupal 7.
function ycs_list($number) {
$query = db_select('field_data_field_active_image', 'a')
->fields('a', array('field_active_image_value', 'entity_id'))
->condition('a.field_active_image_value', 1);
$query->join('node', 'n', 'n.nid = a.entity_id');
$query
->fields('n', array('nid', 'title', 'uid'))
->range(0, $number)
->addTag('node_access')
->execute();
print $query;
return $query;
}
This is how the query prints:
SELECT a.field_active_image_value AS field_active_image_value, a.entity_id AS entity_id, n.nid AS nid, n.title AS title, n.uid AS uid FROM {field_data_field_active_image} a INNER JOIN {node} n ON n.nid = a.entity_id WHERE (a.field_active_image_value = :db_condition_placeholder_0) LIMIT 3 OFFSET 0
It looks right and does work directly in mysql. I have to change :db_conditon_placehoder_0 to 1 and it works doing a direct sql query. I want to pull an array of nodes based upon a condition in the active_image field. Any help would be much appreciated.
Without knowing the actual error you're getting it's a bit tricky to debug your existing code, but I'd advise using the EntityFieldQuery class to do this instead:
function ycs_list($number) {
$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'name_of_node_type') // Remove this line if you don't want to specify a particular node type for the query.
->fieldCondition('field_active_image', 'value', 1)
->range(0, $number)
->addTag('node_access');
// Execute the query and check for results.
$results = $query->execute();
$nodes = array();
if ($results && isset($results['node'])) {
// Load the node objects based on the node ids returned from the query.
$nodes = node_load_multiple(array_keys($results['node']));
}
// If nodes matching your conditions were found you now have an array of fully loaded node objects in $nodes.
}

Resources