I'm stuck; I want to not have the "-" separator on my last item! How can I do that? I know I'm supposed to use count, but I don't know how to go further.
$report = array();
$job = null; //on met la variable a zero
$i = null;
//On extrait les valeurs dans un nouveau tableau à l'aide d'une boucle :
foreach ($values_collaborateurs as $key_collab => $row_collab)//id collab prendra chaque valeur du tableau
{
//ici ne pas mettre de report[key_collab]
//exit(var_dump($values_collaborateurs));
$report[] = $row_collab; // la valeur de id collab = indice collab
//On re extrait les valeurs: boucle du table mission:
//pour chaque élément de $values_missions => id-mission
foreach($values_missions as $key_mission => $row_mission)
{
//ici ne pas mettre de report[key_missions]
// ici la condition de recherche
if ($row_collab[0] == $row_mission[1])
{
$job .= $row_mission[2]." - ";// .= concatenation pr dire s'ajoute a row mission la valeur de job
// rempli le job par des valeurs
}
}
$report[$key_collab][] = $job; //$report = table qui contient chq valeur des key collab, et tout ça tu le stock ds $job
$i = null;
$job = null; //stop - remet le cycle job a zero pour recommencer a null
}
print_r("<pre>\n");
print_r($report);
print_r("<pre>\n");
printf("<br>\n");//passage a la ligne
?>
U can delete last two chars after foreach is completed using strlen...
foreach($values_missions as $key_mission => $row_mission)
{
//ici ne pas mettre de report[key_missions]
// ici la condition de recherche
if ($row_collab[0] == $row_mission[1])
{
$job .= $row_mission[2]." - ";// .= concatenation pr dire s'ajoute a row mission la valeur de job
// rempli le job par des valeurs
}
}
$job = substr($job,0,strlen($job)-2);
Other solution is:
$jobs[] = $row_mission[2]; // instead of: $job .= $row_mission[2] . " - ";
and after foreach will ended:
$job = implode(" - ", $jobs);
Use count() to determine the total number of items and compare it with a counter ($current_mission) that you increment each iteration step.
Then you can append the separator only if the current item is not the last one:
$current_mission = 1;
$total_missions = count($values_missions);
foreach($values_missions as $key_mission => $row_mission)
{
//ici ne pas mettre de report[key_missions]
// ici la condition de recherche
if ($row_collab[0] == $row_mission[1])
{
$job .= $row_mission[2];// .= concatenation pr dire s'ajoute a row mission la valeur de job
if ($current_mission < $total_missions) {
$job .= ' - ';
}
// rempli le job par des valeurs
}
++$current_mission;
}
An alternative is to build an array of strings and use implode().
I highly suggest to not build an array and then use implode, as it's too much overhead for both CPU and memory. If you go for substr($job,0,strlen($job)-2); you are better off with substr($job, 0, -3);, which does exactly the same.
If it's easier to read for you, you can do $job .= ' - ' . $row_mission[2]; and then substr($job, 3);.
On a side note, your code looks buggy:
You use $report[] = $row_collab;, and later $report[$key_collab][], which means you are using $reportboth as un-indexed array and associative array. That your data looks right might just be a coincidence, because if $key_collaband $row_collab have the same value, they overwrite each other.
Related
I recently changed my website from shared hosting to a dedicated server (major upgrade..), and some things didn't work out of the box. One of these things was the INSERTs. I was used to code INSERTS without bothering about having all the columns values in my statement. The missing columns were automatically filled with 0s and threw basic warning I ignored.
I thought it was normal MySQL\MariaDB behaviour. With my new dedicated server (not hosted locally), the database sends an error and refuses to insert the line if all the columns values are not declared in the INSERT statement. This is a problem. I add columns, from time to time, in many tables, as I improve the site's functionalities. I don't want to be revising all the INSERTS in the thousands of lines in my PHP scripts every time I add a column to a table.
So, instead, I created this insert function.
Basically:
Call the function, send an array with table name and key+values I want to insert
Function reads the table name, selects one line, and list the columns name
Function prepares an INSERT with the passed key+values, and generates bulk (depending on the types) values for the columns without values passed
Proceed to INSERT
Now the questions:
Is there a simpler way of doing this?
Am I breaching something?
Is it a recurrent need?
And here the function code:
// INSERTION DB GÉNÉRALE
function insert_db($valeurs)
{
global $date;
global $no;
global $bdd;
// Pour le log
$log = 'Valeurs reçues BDD : ';
foreach ($valeurs as $colonne => $valeur)
{
$log .= $colonne.' = '.$valeur.' || ';
};
// On obtient la table dans $valeurs['db_table']
$resultat = $bdd->query('SELECT * FROM '.$valeurs['db_table'].' LIMIT 1');
$tous_les_champs = array_keys($resultat->fetch(PDO::FETCH_ASSOC)); // On crée un tableau avec toutes les entêtes de colonnes
$champs = array(); // Les champs qui seront mis au début de la requête
$valeurs_preparees = array(); // Les valeurs préparées (avec un : devant) pour mettre dans la deuxième portion de la requête
foreach ($tous_les_champs as $champ_unique) // On valide qu'on a des données pour chaque colonne
{
$valeur = "0";
if (strpos($champ_unique, 'DATE') !== false) { $valeur = $date; }; // Si le titre du champs contiens « DATE », on prends en considération qu'il faut y mettre quelque chose en type datetime
if (strpos($champ_unique, 'RAW_DN') !== false) { $valeur = "0000-00-00 00:00:00"; }; // Pour le champs custom de date de naissance de USAGERS
if (strpos($champ_unique, 'DATE_DEPART') !== false) { $valeur = "0000-00-00 00:00:00"; }; // Si le titre du champs contiens « DATE », on prends en considération qu'il faut y mettre quelque chose en type datetime
if (strpos($champ_unique, 'DESCRIPTION') !== false) { $valeur = "Aucune description"; };
if (strpos($champ_unique, 'COMMENTAIRE') !== false) { $valeur = "Aucun commentaire"; };
if (strpos($champ_unique, 'CREE_PAR') !== false) { $valeur = $_SESSION['DOCTUS'][$no]['ID']; };
if (strpos($champ_unique, 'MODIF_PAR') !== false) { $valeur = $_SESSION['DOCTUS'][$no]['ID']; };
if (strpos($champ_unique, 'CREATEUR') !== false) { $valeur = $_SESSION['DOCTUS'][$no]['ID']; };
if (strpos($champ_unique, 'MODIFICATEUR') !== false) { $valeur = $_SESSION['DOCTUS'][$no]['ID']; };
if (strpos($champ_unique, 'PAYE_') !== false) { $valeur = "1"; };
if (!isset($valeurs[$champ_unique]) || $valeurs[$champ_unique] == "") { $tableau[$champ_unique] = $valeur; }else{ $tableau[$champ_unique] = $valeurs[$champ_unique]; }; $champs[$champ_unique] = $champ_unique; $valeurs_preparees[$champ_unique] = ":".$champ_unique;
};
// On crée les champs pour la requête
$requete_champs = "";
foreach ($champs as $champ_unique)
{
if ($requete_champs != "") { $requete_champs .= ', '; };
$requete_champs .= $champ_unique;
};
// On crée les valeurs pour la requête
$requete_valeurs = "";
foreach ($valeurs_preparees as $valeur_unique)
{
if ($requete_valeurs != "") { $requete_valeurs .= ', '; };
$requete_valeurs .= $valeur_unique;
};
$req_insert_db = $bdd->prepare('INSERT INTO '.$valeurs['db_table'].'('.$requete_champs.') VALUES('.$requete_valeurs.')');
$req_insert_db->execute($tableau);
$id_insert = $bdd->lastInsertId();
// On log l'insertion
$log .= "\n ID inséré : ".$id_insert;
if ($id_insert == 0) { $log .= ' || ERREUR'; };
$fichier = './log/insertions_log.txt';
file_put_contents($fichier, $log, FILE_APPEND);
return $id_insert;
};
The cause is a different configuration of MySql/MariaDb server between old and new server
(see the documentation of Strict SQL Mode for more details).
The cleanest way is to do an ALTER TABLE of all your tables and give to any fields a DEFAULT value (at least to all fields that you don't want to specify a value): in this case the engine don't need all fields in INSERT statements. (see this answer to see the syntax)
I have a little problem, I'm getting around 800 000 datas from a json and I'm trying to insert them into a MongoDB Database. But I reach memory limit (I've set it up to 8GB for testing) while doing this. I think my script isn't optimized but I can't find where. Can you guys help me ? Here is the script :
$jsonResponse = json_decode($content->response);
$datas = $jsonResponse->hits->hits;
// On crée la collection si elle n'éxiste pas
$collection = $connection->createCollection($table->getTableName(), false );
// On enregistre les données dans la collection
foreach ($datas as $data)
{
if(!empty($data) || $data)
{
$document['_id'] = $data->_id; // ID netwoof unique
$document['_updated'] = substr($data->_source->_updated, 0, -3); // Date de dernière MàJ des données
$document['_url'] = $data->_source->_url; // Start URL
// On enregistre ensuite chaque champs définis dans le dashboard
foreach ($fields as $field)
{
// On récupère le nom du champs netwoof
$containerFieldName = $field->getContainerFieldName();
// On fait correspondre notre champ db avec celui netwoof
if( isset( $data->_source->$containerFieldName ) && (!empty($data->_source->$containerFieldName) || $data->_source->$containerFieldName == 0 ) )
$document[$field->getFieldName()] = $data->_source->$containerFieldName;
/*else
$document[$field->getFieldName()] = null;*/
}
foreach ($customFields as $customField)
{
if(!empty($customField->getFieldValue()))
$document[$customField->getFieldName()] = $customField->getFieldValue();
}
// Enregistrement des données
$collection->save($document);
}
// On réinitialise la variable
unset($document);
}
Thanks all for your answer and sorry for my english.
I'm using Codeigniter.
I want to get in my database all the dates that are between two dates
The result for my function is always an empty array.
In my DB dates are this format: 2015-10-21
My model
public function lireListeAchats($selection = "*", $date_debut, $date_fin, $champs_order = "id", $direction_ordre = "ASC", $nombre_limite = NULL, $debut_limite = NULL){
$conditions = "date_achat BETWEEN $date_debut AND $date_fin";
$retour= $this->db->select($selection)
/*à partir de quelle table*/
->from($this->table)
/*déterminer des conditions spécifiques*/
->where($conditions)
/*déterminer un ordre précis*/
->order_by($champs_order, $direction_ordre)
/*déterminer une limite*/
->limit($nombre_limite, $debut_limite)
/*obtenir les résultats (va de pair avec result()*/
->get()
/*retourner les résultats sous forme de tableau*/
->result_array();
return $retour;
}
$date_debut and $date_fin return in this format: 2015-10-01
It's because of $date_debut AND $date_fin, those variables are strings.
Wrap them in quotes '$date_debut' AND '$date_fin'
MySQL is interpreting 2015-10-01 as 2015 minus 10 minus 01.
Use CodeIgniter's error checking:
https://ellislab.com/codeigniter/user-guide/general/errors.html
You have a typo here. It should be either return or retour. Return seems to be better than retour.
public function lireListeAchats($selection = "*", $date_debut, $date_fin, $champs_order = "id", $direction_ordre = "ASC", $nombre_limite = NULL, $debut_limite = NULL){
$conditions = "date_achat BETWEEN $date_debut AND $date_fin";
$return= $this->db->select($selection)
/*à partir de quelle table*/
->from($this->table)
/*déterminer des conditions spécifiques*/
->where($conditions)
/*déterminer un ordre précis*/
->order_by($champs_order, $direction_ordre)
/*déterminer une limite*/
->limit($nombre_limite, $debut_limite)
/*obtenir les résultats (va de pair avec result()*/
->get()
/*retourner les résultats sous forme de tableau*/
->result_array();
return $return;
I will try to explain my case.
I would like to change the wpseo_title, wpseo_metakey, wpseo_metadesc, wpseo_opengraph_type, wpseo_opengraph_image, wpseo_title, and wpseo_opengraph_image_size on the "archive-page" of "custom post"
Because yoast plugin not translated meta tags inside "archive" post. And i need to translate all
I have this code:
function get_archive_seo() {
include 'seo_archive.php';
$tipoSel = get_post_type(get_the_ID());
if(is_post_type_archive( $tipoSel )){
foreach ($traduccionesArchive as $keyTipo => $tipo){
foreach ($tipo as $keyMeta => $palabra){
if($keyMeta == 'opengraph_type' || $keyMeta == 'opengraph_image_size') continue;
icl_register_string ('my-theme', $keyTipo." - ".$keyMeta, $palabra);
}
}
foreach ($traduccionesArchive[$tipoSel] as $key => $palabra){
add_filter( 'wpseo_'.$key, function($nombre) use ( $palabra, $tipoSel, $key ) {
if($key == 'opengraph_type' || $key == 'opengraph_image_size') return $palabra;
return icl_t('my-theme', $tipoSel." - ".$key, $palabra);
});
}
}
}
add_filter( 'wp_head', 'get_archive_seo');
And this is the "seo_archive.php":
$traduccionesArchive['hoteles']['title'] = 'Hotel, Vacaciones en Andalucia';
$traduccionesArchive['hoteles']['metakey'] = 'palabra1, palabra2, palabra3';
$traduccionesArchive['hoteles']['metadesc'] = 'Mapa de Hotel en Andalucia, Costa del Sol, Costa de la Luz y Sierra de Grazalema. El lugar ideal para tus vacaciones.';
$traduccionesArchive['hoteles']['opengraph_type'] = 'object';
$traduccionesArchive['hoteles']['opengraph_image'] = 'http://www.hotel.com/img/logo.png';
$traduccionesArchive['hoteles']['opengraph_image_size'] = 100;
$traduccionesArchive['apartamentos']['title'] = 'Apartamentos de vacaciones Costa del Sol ';
$traduccionesArchive['apartamentos']['metakey'] = 'palabra1, palabra2, palabra3';
$traduccionesArchive['apartamentos']['metadesc'] = 'Mapa de localizacion de los Apartamentos Vacacionales de Hotel. Disfruta de tus vacaciones en familia en la Costa del Sol.';
$traduccionesArchive['apartamentos']['opengraph_type'] = 'object';
$traduccionesArchive['apartamentos']['opengraph_image'] = 'http://www.hotel.com/img/logo.png';
$traduccionesArchive['apartamentos']['opengraph_image_size'] = 100;
$traduccionesArchive['destinos']['title'] = 'Mapa de localizacion de Hotel, Andalucia';
$traduccionesArchive['destinos']['metakey'] = 'palabra1, palabra2, palabra3';
$traduccionesArchive['destinos']['metadesc'] = 'Mapa de Hoteles en Andalucia, en los destinos vacacionales de Costa del Sol, Costa de la Luz y Sierra de Grazalema Andalucia.';
$traduccionesArchive['destinos']['opengraph_type'] = 'object';
$traduccionesArchive['destinos']['opengraph_image'] = 'http://www.hotel.com/img/logo.png';
$traduccionesArchive['destinos']['opengraph_image_size'] = 100;
$traduccionesArchive['ofertas']['title'] = 'Ofertas Hotel Costa del Sol, Costa de la Luz ';
$traduccionesArchive['ofertas']['metakey'] = 'palabra1, palabra2, palabra3';
$traduccionesArchive['ofertas']['metadesc'] = 'Ahorra en tus vacaciones con las ofertas en nuestros hoteles de la Costa del Sol, Costa de la Luz y Andalucia.';
$traduccionesArchive['ofertas']['opengraph_type'] = 'object';
$traduccionesArchive['ofertas']['opengraph_image'] = 'http://www.hotel.com/img/logo.png';
$traduccionesArchive['ofertas']['opengraph_image_size'] = 100;
But now, it not works, but in the past works fine, the filter is form module yoast SEO https://yoast.com/wordpress/plugins/seo/
Y tried with this Wordpress: How to return value when use add_filter?
I'm a little confused because this:
add_filter( 'wpseo_title', function(){return 'foo';}
Works outside the get_archive_seo functions, but not works inside function.
Can anybody help me?
You can use like this, this may help to you.
function title_function_name($title) {
$title = "Your title write here";
return $title;
}
add_filter('wp_title', 'title_function_name', 15);
if (!has_filter('wpseo_title'))
add_filter('wpseo_title', 'title_function_name', 15);
I have the following string. I need to find the position of the last white space.
I have tried the following code:
for ($i = 410; $i < 420; $i++) {
if ($body[$i] == ' ') {
$lastCharacter = $i;
break;
}
}
But it does not return the correct white space position. It return a position in middle of a word.
Dans cette septième étape, les coureurs vont relier Montpellier et
Albi, passant au milieu des vignes de l'arrière-pays pour faire la
jonction entre les Alpes et les Pyrénées, traversant des paysages qui
font toute la saveur du Tour. Dernière étape un peu plate avant un
week-end placé sous le signe de la montagne. Des ascensions de col, la
foule amassée sur les côtés, souffrant avec leu...
$lastSpace = strrpos($string," ");
Doc: strrpos
Use strrpos : http://php.net/manual/en/function.strrpos.php
echo $pos = strrpos($mystring, " ");