Wordpress custom taxonomy hierarchy insert - php

I am having some trouble getting this loop to work properly.
I want to insert Country, State, City, Community from google maps as heiarchy in a custom taxonomy of wordpress. All the variables get set but when it runs through the for loop it only populates and inserts the country or 1st array $loop[0].
I am using $pastID[$d] to save the last term_id to use it as the parent in the next term. If this is just bad let me know.
I have to use Globals as I am connecting with an existing plugin also.
$custom_tax_name = "location";
$loop = array();
$loop[0] = $country = $GLOBALS['custom_array']['country'];
$loop[1] = $state = $GLOBALS['custom_array']['state'];
$loop[2] = $city = $GLOBALS['custom_array']['city'];
$loop[3] = $community = $GLOBALS['custom_array']['community'];
$pastID = array();
$terms = array();
for($i = 0; $i<=3; $i++) {
$d = $i - 1;
if (!empty($loop[$i])){
$term_exist = term_exists( $loop[$i], $custom_tax_name );
if (!$term_exist){
if ($i == 0){
$pastID[$d] = wp_insert_term("$loop[$i]", $custom_tax_name);
} else {
if (empty($pastID[$d]['term_id'])){
$term = get_term_by('name', $loop[$i], $custom_tax_name);
$termParent = $term ? $term->parent : false;
if ($termParent == false){
continue;
}
$pastID[$d] = wp_insert_term("$loop[$i]", $custom_tax_name, array("parent" => $termParent));
} else {
$termParent = $pastID[$d]['term_id'];
$pastID[$d] = wp_insert_term("$loop[$i]", $custom_tax_name, array("parent" => $termParent));
}
}
} else {
$pastID[$d] = $term_exist;
}
$terms[] = $loop[$i];
delete_option('{$custom_tax_name}_children');
} // nothing exist
}

Ok So I was able to figure this out after taking a look and feel a little slow here.
the $pastID needed to have $i variable when setting it and $d when referencing it on the next loop. The code below will create a hierarchy taxonomy up to 4+ deep using my variables for country, state, city, and community. It will check if the variable exist and if it does not it will make sure it has a parent to associate it with or not insert it. Anyways thanks.
for($i = 0; $i<=3; $i++) {
$d = $i - 1;
if (!empty($loop[$i])){
$term_exist = term_exists( $loop[$i], $custom_tax_name );
if (!$term_exist){
if ($i == 0){
$pastID[$i] = wp_insert_term($loop[$i], $custom_tax_name);
} else {
if (empty($pastID[$d]['term_id'])){
$term = get_term_by('name', $loop[$i], $custom_tax_name);
$termParent = $term ? $term->parent : false;
if ($termParent == false){
continue;
}
$pastID[$i] = wp_insert_term($loop[$i], $custom_tax_name, array("parent" => $termParent));
} else {
$termParent = $pastID[$d]['term_id'];
$pastID[$i] = wp_insert_term("$loop[$i]", $custom_tax_name, array("parent" => $termParent));
}
}
} else {
$pastID[$d] = $term_exist;
}
$terms[] = $loop[$i];
delete_option('{$custom_tax_name}_children');
} // nothing exist
}

Related

PHP add unique User array to newly created array while iterating over Episode authors object

Hi i am iterating over Episodes getting array of authors and inside this loop i want to gather information about each author. But there is problem, i just need the information about each author once.
This is my approatch, but wrong. and the code i am trying to make. Please help. I tried also in_array, and array_filter but without success.
$presentUsers = [];
$pUi = 0;
if ($isAuthor == true){
if ($project->getType() == 1) {
$episodes = $project->getComic()->getComicEpisodes();
foreach ($episodes as $comicEpisode) {
foreach ($comicEpisode->getProject()->getAccount() as $author) {
if ($author->getUser()->getId() == $this->getUser()->getId()) {
$comicEpisode->setIsMine(true);
$comicEpisode->setRevenue($author->getRevenue());
$comicEpisode->setIncome($author->getIncome());
}
if (empty($presentUsers)){
$presentUsers[$pUi]['Id'] = $author->getUser()->getId();
$presentUsers[$pUi]['Username'] = $author->getUser()->getUsername();
$presentUsers[$pUi]['FirstName'] = $author->getUser()->getFirstName();
$presentUsers[$pUi]['LastName'] = $author->getUser()->getLastName();
$presentUsers[$pUi]['VisibleName'] = $author->getUser()->getVisibleName();
$presentUsers[$pUi]['AvatarFileName'] = $author->getUser()->getAvatarFileName();
$presentUsers[$pUi]['Occupation'] = $author->getUser()->getOccupation();
$presentUsers[$pUi]['LastOnline'] = $author->getUser()->getLastOnline();
$pUi++;
}else{
if (!in_array($presentUsers, ['Id'=>$author->getUser()->getId()]))
{
$presentUsers[$pUi]['Id'] = $author->getUser()->getId();
$presentUsers[$pUi]['Username'] = $author->getUser()->getUsername();
$presentUsers[$pUi]['FirstName'] = $author->getUser()->getFirstName();
$presentUsers[$pUi]['LastName'] = $author->getUser()->getLastName();
$presentUsers[$pUi]['VisibleName'] = $author->getUser()->getVisibleName();
$presentUsers[$pUi]['AvatarFileName'] = $author->getUser()->getAvatarFileName();
$presentUsers[$pUi]['Occupation'] = $author->getUser()->getOccupation();
$presentUsers[$pUi]['LastOnline'] = $author->getUser()->getLastOnline();
$pUi++;
}
}
}
}
}
}else{
die('You are not the author of this project.');
}
Okay i done it like this
if (empty($presentUsers)){
$presentUsers[$pUi]['Id'] = $author->getUser()->getId();
$presentUsers[$pUi]['Username'] = $author->getUser()->getUsername();
$presentUsers[$pUi]['FirstName'] = $author->getUser()->getFirstName();
$presentUsers[$pUi]['LastName'] = $author->getUser()->getLastName();
$presentUsers[$pUi]['VisibleName'] = $author->getUser()->getVisibleName();
$presentUsers[$pUi]['AvatarFileName'] = $author->getUser()->getAvatarFileName();
$presentUsers[$pUi]['Occupation'] = $author->getUser()->getOccupation();
$presentUsers[$pUi]['LastOnline'] = $author->getUser()->getLastOnline();
$pUi++;
}else{
$found = 0;
foreach ($presentUsers as $presentUser){
if ($presentUser['Id'] == $author->getUser()->getId()){
$found = 1;
break;
}
}
if ($found != 1)
{
$presentUsers[$pUi]['Id'] = $author->getUser()->getId();
$presentUsers[$pUi]['Username'] = $author->getUser()->getUsername();
$presentUsers[$pUi]['FirstName'] = $author->getUser()->getFirstName();
$presentUsers[$pUi]['LastName'] = $author->getUser()->getLastName();
$presentUsers[$pUi]['VisibleName'] = $author->getUser()->getVisibleName();
$presentUsers[$pUi]['AvatarFileName'] = $author->getUser()->getAvatarFileName();
$presentUsers[$pUi]['Occupation'] = $author->getUser()->getOccupation();
$presentUsers[$pUi]['LastOnline'] = $author->getUser()->getLastOnline();
$pUi++;
}
}

Laravel conditional statement with each() result error

Partly confused (still) because the variable $investment_type resulting of "Creating default object from empty value" when I follow this previous question of mine Laravel list() with each() function error with deprecated function.
This is the original code.
$assetsData = ClientPropertyManagement::find($assets_id);
$investmentType = Input::get('investmenttype'.$assets_id);
$legalname = Input::get('legalname'.$assets_id);
$ownership = Input::get('ownership'.$assets_id);
$tic = Input::get('tic'.$assets_id);
$entity_id = Input::get('entity_id'.$assets_id);
foreach($investmentType as $investment_type) {
list($key,$value) = each($legalname);
list($key,$valueOwner) = each($ownership);
list($key,$valueTic) = each($tic);
list($key,$valueEntityId) = each($entity_id);
if($valueEntityId == 0) {
$assetEntity = new ClientEntityManagement;
$assetEntity->property_id = $assetsData->property_id;
$assetEntity->client_id = $id;
} else {
$assetEntity = ClientEntityManagement::find($valueEntityId);
}
$assetEntity->investment_type = $investment_type;
$assetEntity->entity_name = $value;
$assetEntity->ownership = $valueOwner;
$assetEntity->ticnum = $valueTic;
$assetEntity->save();
}
Here's what I did in my code.
foreach( $investmentType as $key => $investment_type ) {
$assetEntity->investment_type = $investment_type;
$assetEntity->entity_name = $legalname[$key];
$assetEntity->ownership = $ownership[$key];
$assetEntity->ticnum = $tic[$key];
if ( $entity_id[$key] == 0 ) {
$assetEntity = new ClientEntityManagement;
$assetEntity->property_id = $assetsData->property_id;
$assetEntity->client_id = $id;
} else {
$assetEntity = ClientEntityManagement::find($investment_type);
}
$assetEntity->save();
}
The problem is that $assetEntity isn't created yet, and you are trying to use as an object. To solve that, you need to change the position where you instantiate the object and create the variable $assetEntity:
foreach( $investmentType as $key => $investment_type ) {
if ( $entity_id[$key] == 0 ) {
$assetEntity = new ClientEntityManagement;
$assetEntity->property_id = $assetsData->property_id;
$assetEntity->client_id = $id;
} else {
$assetEntity = ClientEntityManagement::find($investment_type);
}
$assetEntity->investment_type = $investment_type;
$assetEntity->entity_name = $legalname[$key];
$assetEntity->ownership = $ownership[$key];
$assetEntity->ticnum = $tic[$key];
$assetEntity->save();
}
That way $assetEntity will be created, and then you populate the other attributes.
Also, you may want to use the IoC Container and replace the new ClientEntityManagement with App::make('ClientEntityManagement'). Read more at https://laravel.com/docs/4.2/ioc

"Cannot get return value of a generator that hasn't returned " php backtracking

I am trying to do backtracking to solved a problem but I get this error:
Error: genator hasn´t returned
Fisrt I will introduce the main problem that the software must resolve:
I have been trying to create the software for a hospital, this
software must create a schedule with the doctors for each day. Each
day must have 5 assigned doctors, one for a specialty called "trauma",
another for "ucr" and another for "box13".
Before assigning doctors, the user must enter the number of holes of
each type that doctor can do that month. So I know how many "trauma",
"ucr" or "box13" have any doctor that month.
Aaah! one more thing, you can not assign a doctor two days in a row.
So I decided to create a backtracking algorithm, the problem is that I am getting a Generator object at the end of the execution but I don´t get a valid return.
function bt($ps){
if($ps->is_solution()){
return $ps->get_solution();
}
else{
yield from $ps->successors();
}
}
class Briker_vc_PS{
public function __construct( $decisiones, $diasTotalFinal, $fechaInicio, $box13, $ucr, $trauma, $numGuardiasAsig){
$this->decisiones= $decisiones;
$this->diasTotalFinal = $diasTotalFinal;
$this->fechaInicio = $fechaInicio;
$this->box13 = $box13;
$this->ucr = $ucr;
$this->trauma = $trauma;
$this->numGuardiasAsig = $numGuardiasAsig;
}
public function is_solution(){
return $this->numGuardiasAsig == $this->diasTotalFinal*5;
}
public function get_solution(){
return $this->decisiones;
}
public function state(){
return $this->decisiones[$this->fechaInicio];
}
public function successors(){
if( array_key_exists( $this->fechaInicio, $this->decisiones) == false ){
$this->decisiones[$this->fechaInicio] = [];
}
if( array_key_exists( 'ids', $this->decisiones[$this->fechaInicio]) == false ){
$this->decisiones[$this->fechaInicio]['ids'] = [];
}
if( array_key_exists( $this->fechaInicio ,$this->decisiones) and array_key_exists( 'box13' ,$this->decisiones) and array_key_exists( 'trauma' ,$this->decisiones) and array_key_exists( 'ucr' ,$this->decisiones)){
if( (count($this->decisiones['trauma'])==1) and (count($this->decisiones['ucr'])==2) and (count($this->decisiones['box13'])==2) ){
$this->fechaInicio = date("Y-m-d",strtotime($this->fechaInicio." +1 day"));
$this->decisiones[$this->fechaInicio]['date'] = $this->fechaInicio;
}
}
$anterior = date("Y-m-d",strtotime($this->fechaInicio." -1 day"));
$Lista=[];
if( array_key_exists( 'trauma' ,$this->decisiones) == false ){
foreach($this->trauma as $key => $val){
if( (in_array($key, $this->decisiones[$this->fechaInicio]['ids']) == false) and (in_array($key, $this->decisiones[$anterior]['ids']) == false) ){
$decisions= $this->decisiones;
$decisions[$this->fechaInicio]['trauma'] = [$key];
$auxtra= $this->trauma;
if($auxtra[$key] -1 == 0){
unset($auxtra[$key]);
}else{
$auxtra[$key] = $auxtra[$key] -1;
}
$num = $this->numGuardiasAsig +1 ;
$decisions[$this->fechaInicio]['ids'][] = $key;
yield from bt(new Briker_vc_PS( $decisions, $this->diasTotalFinal, $this->fechaInicio, $this->box13, $this->ucr, $auxtra, $num));
}
}
}
if( (array_key_exists( 'box13' ,$this->decisiones) == false) or (count($this->decisiones['box13'])<2) ){
foreach($this->box13 as $key => $val){
if( (in_array($key, $this->decisiones[$this->fechaInicio]['ids']) == false) and (in_array($key, $this->decisiones[$anterior]['ids']) == false) ){
$decisions= $this->decisiones;
if(array_key_exists( 'box13' ,$this->decisiones) == false){
$decisions[$this->fechaInicio]['box13'] = array();
}
$decisions[$this->fechaInicio]['box13'][] = $key;
$auxbox13= $this->box13;
if($auxbox13[$key] -1 == 0){
unset($auxbox13[$key]);
}else{
$auxbox13[$key] = $auxbox13[$key] -1;
}
$num = $this->numGuardiasAsig +1 ;
$decisions[$this->fechaInicio]['ids'][] = $key;
yield from bt( new Briker_vc_PS( $decisions, $this->diasTotalFinal, $this->fechaInicio, $auxbox13, $this->ucr, $this->trauma, $num));
}
}
}
if( (array_key_exists( 'ucr' ,$this->decisiones) == false) or (count($this->decisiones['ucr'])<2) ){
foreach($this->ucr as $key => $val){
if( (in_array($key, $this->decisiones[$this->fechaInicio]['ids']) == false) and (in_array($key, $this->decisiones[$anterior]['ids']) == false) ){
$decisions= $this->decisiones;
if(array_key_exists( 'ucr' ,$this->decisiones) == false){
$decisions[$this->fechaInicio]['ucr'] = array();
}
$decisions[$this->fechaInicio]['ucr'][] = $key;
$auxucr= $this->ucr;
if($auxucr[$key] -1 == 0){
unset($auxucr[$key]);
}else{
$auxucr[$key] = $auxucr[$key] -1;
}
$decisions[$this->fechaInicio]['ids'][] = $key;
$num = $this->numGuardiasAsig +1 ;
yield from bt(new Briker_vc_PS( $decisions, $this->diasTotalFinal, $this->fechaInicio, $this->box13, $auxucr, $this->trauma, $num));
}
}
}
}
protected $GuardiasMedico;
protected $decisiones;
}
And this is the main program
$month = $_REQUEST['mes'];
$year = $_REQUEST['any'];
$fecha_inicio = "01-".$month."-".$year;
// fisrt i get the number of "trauma", "ucr" and "box13" for each doctor
// And i create a array with it with key the doctor_id
$db = new SQLite3($dbname);
$result = $db->query('SELECT m.id, m.nombre, m.apellido, mgm.ucr, mgm.trauma, mgm.box13 FROM medico AS m INNER JOIN MedicoGuardiaMes AS mgm ON m.id = mgm.doctor_id WHERE m.borrado = 0 AND mgm.mes = '.$month.' AND mgm.any = '.$year);
$box13 = [];
$ucr = [];
$trauma = [];
while($res = $result->fetchArray()){
$box13[$res['id']] = $res['box13'];
$ucr[$res['id']] = $res['ucr'];
$trauma[$res['id']] = $res['trauma'];
}
// I create the solution array and add the last day from the previous month
$dataBaseDecisiones = [];
$anterior = date("Y-m-d",strtotime($fecha_inicio." -1 day"));
$dataBaseDecisiones[$anterior] = [];
$dataBaseDecisiones[$anterior]['ids'] = [];
$diasTotalFinal=cal_days_in_month(CAL_GREGORIAN, $month, $year);
// Finally I create the initial object and starts the backtracking
$initial_ps = new Briker_vc_PS($dataBaseDecisiones, $diasTotalFinal, $fecha_inicio, $box13, $ucr, $trauma, $numGuardiasAsig);
var_dump( bt($initial_ps)->getReturn() );
I don´t know why this code is not working or if I am using yield the right way.
The problem that is reported happens because of the last line in your code:
bt($initial_ps)->getReturn();
When bt executes the else part it performs a recursive search until there is a return, and then it yields that value. But that does not finish the iterator's results and this yielded value is not considered the iterator's return value. So getReturn() triggers the exception you got.
You don't explain what you intend to get as output in that var_dump. If you want to output all the yielded results, then collect all those results first, for instance with iterator_to_array:
$iter = bt($initial_ps);
print_r(iterator_to_array($iter));
And only then you can execute:
print_r($iter->getReturn());

Catch Tweets with JSON and sort by likes?

I am currently running a wordpress backend and want to display some tweets based on hastags on my website. For the general API request and database storage, I use this function:
private function parseRequest($json) {
$tmp = $json;
$result = array();
if (isset($json['statuses'])) {
$tmp = $json['statuses'];
}
if (isset($tmp) && is_array($tmp)){
foreach ($tmp as $t) {
$this->image = null;
$this->media = null;
$tc = new \stdClass();
$tc->feed_id = $this->id();
$tc->id = $t['id_str'];
$tc->type = $this->getType();
$tc->nickname = '#'.$t['user']['screen_name'];
$tc->screenname = (string)$t['user']['name'];
$tc->userpic = str_replace('.jpg', '_200x200.jpg', str_replace('_normal', '', (string)$t['user']['profile_image_url']));
$tc->system_timestamp = strtotime($t['created_at']);
$tc->text = $this->getText($t);
$tc->userlink = 'https://twitter.com/'.$t['user']['screen_name'];
$tc->permalink = $tc->userlink . '/status/' . $tc->id;
$tc->media = $this->getMedia($t);
#$tc->additional = array('shares' => (string)$t['retweet_count'], 'likes' => (string)$t['favorite_count'], 'comments' => (string)$t['reply_count']);
if ($this->isSuitablePost($tc)) $result[$tc->id] = $tc;
}
}
return $result;
}
Now I am looking for a function that counts all the variable in the "additional array together e.g. shares + likes + comments and sorts all posts based on the resulting number.
I am using the standard wordpress sql database. I cannot find a solution or I am just blind.
Thanks in regards
You could use a simple usort function:
usort($tc, function($a, $b) {
$a_sum = array_sum($a->additional);
$b_sum = array_sum($b->additional);
if ($a_sum == $b_sum) {
return 0;
}
return ($a_sum < $b_sum) ? -1 : 1;
});

PHP Array Nominal Indexes with Strings

I have a PHP application that takes a CSV in input; in the first column I have both category and subcategory splitted by a '|'. I have to put this stuff in a Open Cart DB, which has the same table for Category and Subcategory (a column "parent_id" indicates the category_id of the Category).
I thought to build a class with all the fields needed as follows:
class Categorie {
public $category_id;
public $parent_id;
public $image;
public $top;
public $column;
public $sort_order;
public $status;
public $date_modified;
public $date_added;
public $language_id;
public $name;
public $description;
public $meta_description;
public $meta_keywords;
}
Then I analyze the data:
$categorie = array();
while ( ( $riga_file = fgetcsv( $file, 100000, "\t" ) ) !== false )
{
$array_el = count( $riga_file );
for( $el_cur = 0; $el_cur < $array_el; $el_cur++ )
{
switch ( $el_cur )
{
case 0:
$colonne = explode( "|", $riga_file[$el_corr] );
$categoria = new Categorie();
$categoria->image = "";
$categoria->top = 1;
$categoria->column = 1;
// ... bla adding description data
if( $categorie[$colonne[0]] == NULL ) // (1)
{
$categoria->name = $colonne[0];
$categoria->category_id = $id_categoria;
$categoria->parent_id = 0;
$categorie[$colonne[0]] = $categoria;
$id_categoria++;
}
if( $colonne[1] != NULL ) // (2)
{
$categoria->name = $colonne[1];
if( $categorie[$colonne[1]] == NULL )
{
$categoria->category_id = $id_categoria;
$categoria->parent_id = $categorie[$colonne[0]]->category_id;
$categorie[$colonne[1]] = $categorie;
$id_categoria++;
}
}
break;
}
I should have an array filled with a collection of unique objects like:
// OUT(3)
Category 1
Subcategory 1
Category 2
Subcategory 2...
If I put echoes of $categoria (not $categorie) inside (1) and (2), I see exactly what I wrote down in OUT(3), which leads me to think that my "engine" is correct. The problems come when I try to search into the array:
echo "<table border='1'>";
foreach( $categorie as $value )
{
echo "<tr>
<td>$value->category_id</td>
<td>$value->parent_id</td>
<td>$value->name</td>
</tr>";
}
echo "</table>";
because I don't get Categories at all, and most but not all Subcategories.
Am I doing something wrong with "search engine" or I misunderstood something with PHP Arrays (probably because I come from C++ and this php is f**king my mind)?
I solved the problem, or better: problems.
1) I mispelled a variable: in (2) I wrote:
$categorie[$colonne[1]] = $categorie;
The correct writing is:
$categorie[$colonne[1]] = $categoria;
2) The bigger problem was from my "unknowing" of PHP, in fact, fixed the problem 1, I got an output like:
subcategory1
subcategory1
subcategory2
subcategory2
and so on. This lead me to guess that when I do:
$categorie[$colonne[1]] = $categoria;
PHP doesn't copy the values inside, but uses addresses instead. Follows the right code:
switch ( $el_corr )
{
case 0: // Categorie e sottocategorie
$colonne = explode( "|", $riga_file[$el_corr] );
$categoria = new Categorie();
$categoria->image = "";
$categoria->top = 1;
$categoria->column = 1;
$categoria->sort_order = 0;
$categoria->status = 1;
// Category_Description Campi
$categoria->language_id = 1;
$categoria->name = $colonne[0];
$categoria->description = "";
$categoria->meta_description = "";
$categoria->meta_keywords = "";
////////////////////////
if( $categorie[$colonne[0]] == NULL )
//if( !trova_categorie( $colonne[0], $categorie ) )
{
$categoria->name = $colonne[0];
$categoria->category_id = $id_categoria;
$categoria->parent_id = 0;
$categorie[$colonne[0]] = $categoria;
$id_categoria++;
}
$categoria = new Categorie();
$categoria->image = "";
$categoria->top = 1;
$categoria->column = 1;
$categoria->sort_order = 0;
$categoria->status = 1;
// Category_Description Campi
$categoria->language_id = 1;
$categoria->name = $colonne[0];
$categoria->description = "";
$categoria->meta_description = "";
$categoria->meta_keywords = "";
if( $colonne[1] != NULL )
{
$categoria->name = $colonne[1];
if( $categorie[$colonne[1]] == NULL )
//if( !trova_categorie( $colonne[1], $categorie ) )
{
$categoria->category_id = $id_categoria;
$categoria->parent_id = $categorie[$colonne[0]]->category_id;
$categorie[$colonne[1]] = $categoria;
$id_categoria++;
}
}
break;
}

Categories