I wrote query in php file ,my query is:
$query = "SELECT cc.NAME complex_check_name,f.name server_name,
sgk.NAME single_check_name,cc.operator
FROM complex_check cc,
lnksinglechecktocomplexcheck lk,
single_checks sgk,
functionalci f ,
lnkconfigurationitemtosinglecheck lkcg
WHERE cc.id = lk.complex_check_id AND
sgk.id = lk.single_check_id and
sgk.id = lkcg.single_check_id AND
lkcg.config_item_id = f.id ";
if ($result=mysqli_query($link,$query))
{
while ($obj=mysqli_fetch_object($result))
{
$list= $obj->complex_check_name .
"#".
$obj->server_name .
";".
$obj->single_check_name .
$obj-> operator;
echo $list .'<br>';
}
}
The result is :
test_com_check_sep01#INFRASEP01;cpu check sep01&
test_com_check_sep01#INFRASEP01;DB check sep01&
test_com_check_sep01#INFRASEP01;disk space check sep01&
test_com_check_sep02#INFRASEP02;cpu check sep02||
test_com_check_sep02#INFRASEP02;db check sep02||
test_com_check_sep02#INFRASEP02;disk space check sep02||
How can I concatenate the string as:
"test_com_check_sep01=INFRASEP01;cpu check sep01&INFRASEP01;DBcheck sep01&INFRASEP01;disk space check sep01"
"test_com_check_sep02=INFRASEP02;cpu check sep02||INFRASEP02;db check sep02||INFRASEP02;disk space check sep02"
You could store the values into an array and implode afterwards.
$check = array();
if($result = mysqli_query($link,$query)) {
while($obj = mysqli_fetch_object($result)) {
// If value is not stored in check array proceed
if(!in_array($obj->complex_check_name,$check))
$list[$obj->complex_check_name][] = $obj->complex_check_name."=";
$list[$obj->complex_check_name][] = $obj->server_name.";".$obj->single_check_name.$obj->operator;
// Store in check array
$check[] = $obj->complex_check_name;
}
// Loop through stored rows and implode with break
foreach($list as $array) {
echo implode("<br />",$array);
}
}
try this
$concat1 = '';
$concat2 = '';
if ($result=mysqli_query($link,$query))
{
while ($obj=mysqli_fetch_object($result))
{
if($obj->server_name == 'INFRASEP01'){
concat1 .= $obj->complex_check_name . "#".$obj->server_name .";". $obj->single_check_name . $obj-> operator;
}else{
concat2 .= $obj->complex_check_name . "#".$obj->server_name .";". $obj->single_check_name . $obj-> operator;
}
}
}
echo $concat1 .'<br>'.$concat2;
Assuming you want to keep the lines separate for use, you could do this
$list = array("INFRASEP01", "INFRASEP01", "INFRASEP02");
$concatINFRASEP01 = "";
$concatINFRASEP02 = "";
for($lineCounter = 0; $lineCounter < sizeof($list); $lineCounter++)
if(strpos($list[$lineCounter], "INFRASEP01") !== false){
//Found it
$concatINFRASEP01 .= " " . $list[$lineCounter];
}
else if(strpos($list[$lineCounter], "INFRASEP02") !== false){
$concatINFRASEP02 .= " " . $list[$lineCounter];
}
NOTE: I did not test this code so there may be errors.
If you do not need the $list array, then you can do as #Malakiof suggested.
EDIT (01/22/2015): I have improved my answer but left the old one there in case I misunderstood.
//In your case the rows come from the $obj (which most would call $row)
$listOfRows = array("test_com_check_sep01#INFRASEP01;cpu check sep01&","test_com_check_sep01#INFRASEP01;DB check sep01&", "test_com_check_sep02#INFRASEP02;cpu check sep02||");
//Create this array as you go through each row by adding the server_name
//to this array. You can skip making this array and simply make the
//unique array by checking if the array contains the server_name.
$listServerNames = array("INFRASEP01","INFRASEP02","INFRASEP01", "INFRASEP02", "INFRASEP01");
//Only have unique server names to avoid duplicates
$listUniqueServerNames = array_unique($listServerNames);
//this will be your list of concatenated strings
$concatByServerName = array();
//Go through the unique server names one by one
foreach($listUniqueServerNames as $serverName)
//While looking at each unique server name, look through the rows
foreach($listOfRows as $line)
if(strpos($line, $serverName) !== false){
//Found it
if(array_key_exists($serverName, $concatByServerName))
$concatByServerName[$serverName] .= " " . $line;
else
$concatByServerName[$serverName] = $line;
}
If the $listOfRows is very large, consider making a copy of $listOfRows and removing the lines from $listOfRows when you add them to $concatByServerName.
Although this is not the best way to do it, I am trying to keep it simple in order for you to be able to get it to work, while fully understanding what is happening. You can easily improve on this code by looking at your project and streamlining these tasks.
Related
I need to compare two CSV file that both contain two columns: ID and URL and check if the URL are differents. The two file normally, are the same but sometimes it can change. So i have to compare if the ID is the same and if the URL has change. I would like do this with a multidimensional loop (both of files are very big). But i don't understand why at the first match, the loop is stopped.
I try to do this with a while loop:
while ($file_odierno_fr = fgetcsv($product_dinamica_fr, 0, ";", '"')) {
while ($file_precedente_fr = fgetcsv($product_dinamica_fr_pre, 0, ";", '"' )) {
// the index [1] is the URL and ID is the index [0]
if ($file_odierno_fr[1] !== $file_precedente_fr[1] && $file_odierno_fr[0] == $file_precedente_fr[0]){
$textMail .= "\n\nURL file odierno: <b>".$file_odierno_fr[1]. "</b>\nURL file pecedente: <b>". $file_precedente_fr[1] . "</b>\n\n";
fputcsv($file,array($file_odierno_fr[1], $file_precedente_fr[1]),";");
$sendMail = TRUE;
}
}
}
fclose($product_dinamica_fr);
fclose($product_dinamica_fr_pre);
But when igo to debug this, i get juste the first match and the rest is ignored. I change some URL in the file for be sure that all is working.
I think that i can't do while loop like this, but i'm not sure. There is a way for do that with while loop?
Please try to following code and give a feedback:
$separator = ";";
$enclosure = '"';
$lineSize = 0;// 0 := unlimited
$textMail = "";
while($lineNow = fgetcsv($product_dinamica_fr, $lineSize, $separator, $enclosure))
{
while($linePre = fgetcsv($product_dinamica_fr_pre, $lineSize, $separator, $enclosure))
{
$idNow = trim($lineNow[0]);
$idPre = trim($linePre[0]);
$urlNow = trim($lineNow[1]);
$urlPre = trim($linePre[1]);
// Compare IDs first. If they are not the same, then skip this line
if($idNow != $idPre)
continue;
// If URLs are the same then skip this line
if( $urlNow == $urlPre)
{
continue;
}
// Set email flag and add info to e-mail content
$sendMail = TRUE;
$textMail .= "\n\nURL file odierno: <b>$urlNow</b>\nURL file pecedente: <b>$urlPre</b>\n\n";
// Write the difference to local file
fputcsv($file, [$urlNow, $urlPre], ";");
}
rewind($product_dinamica_fr_pre);
}
fclose($product_dinamica_fr);
fclose($product_dinamica_fr_pre);
echo $textMail;
Want to create a php variable using text before and after the value of another variable.
variable variables. But have only seen examples of assignment with no text.
$vsBOA_W[]=$rows['vsBOA_W'];
// BOA = team 3-char abbreviation. Looking for something similar to above but insert 3-char abbreviations based on a input file.
$numOfTeams = 3; // Determined from external source
$teamAbbr = array("BOA","CAA","CHN"); // For simplicity for this example. This array would normally be created from an external source.
for($i=0; $i<$numOfTeams; $i++) { // I know I can use size of array instead of nunOfTeams. That's not the issue.
echo $teamAbbr[$i]."<br>"; // for testing
$$("vs".{'$teamAbbr[$i]'}."_W[]"} = $rows['$$("vs".{'$teamAbbr[$i]'}."_W"}']; // a total guess
}
I expect the end result to look like:
$vsBOA_W[]=$rows['vsBOA_W'];
for BOA
Update #2: I tried the following (breaking down each step) and get the same error on $$TeamWins assignment.
for($i=0; $i<$numOfTeams; $i++) {
echo $teamAbbr[$i]."<br>";
$TeamWins = 'vs' . $teamAbbr[$i] . '_W';
echo "TeamWins=$TeamWins<br>";
$TeamWinsHold = $rows[$TeamWins];
echo "TeamWinsHold=$TeamWinsHold<br>";
$$TeamWins[] = $TeamWinsHold;
}
Update #3:
for($i=0; $i<$numOfTeams; $i++) {
echo $teamAbbr[$i]."<br>";
$TeamWins = 'vs' . $teamAbbr[$i] . '_W';
echo "TeamWins=$TeamWins<br>";
$TeamWinsHold = $rows[$TeamWins];
echo "TeamWinsHold=$TeamWinsHold<br>";
${$TeamWins}[] = $TeamWinsHold;
}
foreach(${$TeamWins} as $value) {
echo "value=$value<br>"; // only displays last element or value assigned from above loop.
}
Update #4 (final):
$teamW = array();
$teamL = array();
for($i=0; $i<$numOfTeams; $i++) {
//echo $teamAbbr[$i]."<br>";
$teamWName = 'vs' . $teamAbbr[$i] . '_W';
$teamLName = 'vs' . $teamAbbr[$i] . '_L';
//echo "teamWName=$teamWName<br>";
//echo "teamLName=$teamLName<br>";
$teamW[$teamWName] = $rows[$teamWName];
$teamL[$teamLName] = $rows[$teamLName];
}
I don't quite understand the interplay with the rows in your example. But going by your guess assignment, you can always simplify, by forming the variable name upfront:
<?php
$rows = ['xFOOy'=>[], 'xBARy'=>[], 'xBAZy'=>[]];
$items = ['FOO', 'BAR', 'BAZ'];
foreach($items as $abbr)
{
$name = 'x' . $abbr . 'y';
${$name}[] = $rows[$name];
}
But, I'd say you'd be better off with a keyed array than variable variables, as it makes for easier inspection, and there is less chance of namespace clashes.
I have a recurring need to merge two arrays of information. This is happening very often and run possibly 20+ times per page load, so I want to ensure I am attacking this in the most speed-friendly efficient way.
The function receives a list of text keywords and creates a simple unique array of the keywords.
The challenge is then taking these keywords, and getting their associated filenames.html from a database (I used medoo, but that's irrelevant) and be able to present 2 different link types based on the result, which are :
A) where the filename.html exists (or)
B) to a .php file that can handle the keyword as a query (i.e., a static file for the keyword doesn't exist so instead send the user to a .php?=the_keyword to present an appropriate page).
I am somewhat confident that I have made this more elongated that it could be - This is how I am approaching this so far:
$unique_best_keywords = array_unique($best_keywords);
$keywords_to_display = array();
$keywords_to_find = array();
foreach ($unique_best_keywords as $keyword) {
unset($keyword_to_clean);
if (in_array($keyword, $flagged_keywords, TRUE) !== TRUE) {
$keyword_to_clean = strtolower(trim($keyword));
$keyword_to_clean = preg_replace('/[^a-z0-9-]/', '-', $keyword_to_clean);
$keyword_to_clean = preg_replace('/-+/', "-", $keyword_to_clean);
$keywords_to_display[] = array (
"anchor_text" => trim($keyword),
"file_name" => $keyword_to_clean);
}
}
The example result here would be anchor_text: "jobs at apple" and file_name: "jobs-at-apple".
The keyword with dashes in it, is the index in my database to query for matching static html files - so I approach this like the following:
if (isset($keywords_to_display) && !empty($keywords_to_display)) {
foreach ($keywords_to_display as $keyword_to_call_from_db) {
$keywords_to_find[] = $keyword_to_call_from_db['file_name'];
}
unset($keyword_topic_view_links);
$keyword_topic_view_links = $database->select("my_database_table", array(
"filename_dot_html"), array("unique_filename_index" => $keywords_to_find)); // medoo db query
}
}
if (isset($keyword_topic_view_links) && is_array($keyword_topic_view_links)) {
$view_links = array();
foreach ($keyword_topic_view_links as $a_link) {
$view_links[] = $a_link['filename_dot_html'];
}
}
if (isset($keyword_topic_view_links) && isset($keywords_to_display)) {
foreach ($keywords_to_display as $keyword) {
if (count($view_links) < 1) {
// Send all keywords to the .php file to present a nice page -- dynamic!
unset($keyword_display,$keyword_display_file);
$keyword_display = $keyword['anchor_text'];
$keyword_display_file = $keyword['file_name'];
$html_output .= '' . $keyword_display . ' ';
} else {
// Send some topics views to static html pages--
unset($keyword_display,$keyword_display_file,$keyword_display_file_html);
$keyword_display = $keyword['anchor_text'];
$keyword_display_file = $keyword['file_name'];
$keyword_display_file_html = "$keyword_display_file.html";
if (in_array($keyword_display_file_html, $view_links) !== TRUE) {
// Keyword WAS NOT in the db array!
$html_output .= '' . $keyword_display . ' ';
} else {
// Keyword WAS IN in the db array! Yay!
$html_output .= '' . $keyword_display . ' ';
}
}
}
}
Any advice / optimisations would be greatly appreciated.
I've written a script that checks bulk input of names received via a textarea and omits all values that are already in the database. It works if you enter just one repeated name. If you enter two or more, it will filter out the first repeated name, treat the rest as unique names and insert them in the database. I can't figure out why.
Firstly, this is an array that is built in another part of the script. It's generated from a database query:
Array
(
[0] => john
[1] => peter
[2] => max
[3] => jake
)
This array is referred to as $onlyHandles. Then this is the script:
if((isset($_POST['extract']) && !empty($_POST['extract']))){
$handles = trim($_POST['extract']);
$handles = explode("\n", $handles);
if(count($handles)>200){
echo 'error';
exit(1);
}
foreach($handles as $handle) {
$handleRep = strtolower(str_replace('#','',$handle));
$handleClean = str_replace(str_split('\\/:*?&"<>=+-#%$|'), ' ', $handleRep, $count);
if ($count > 0) {
echo 'error';
exit(1);
}
else{
if (in_array($handleClean, $onlyHandles)){
$delmessage .= "<p>".$handleClean." is already in your list.</p>";
}
else{
$sqlIns = "INSERT INTO...blah blah blah)";
$resultIns = mysql_query($sqlIns);
$resInsArr[] = array($resultIns);
}
}
}
$countresIns = count($resInsArr);
if ($countresIns > 0){
$delmessage .= "<p>User(s) added to list succesfully!</p>" ;
}
}
Now, if you enter "john" in the textarea, it will shout that the name already exists. If you enter "john" and "max" it will omit john and add max.
Any help would be greatly appreciated.
P.S. regarding the query format, I know, I know, thanks!
I would like to give U some idea about how to achieve it:
Replace the first line:
if((isset($_POST['extract']) && !empty($_POST['extract']))){
through
if((!empty($_POST['extract']))){
because !empty already guives U the guaranty that it isset
I am suspescting some special chars in play
U could also use the power of Regular Expression to replace the unneeded chars
in replacing:
Line 12: $handleClean = str_replace(str_split('\\/:*?&"<>=+-#%$|'), ' ', $handleRep, $count);
Through:
$handleClean = preg_replace("/\[\/:\*?&\"<>=\+-#%\$\|\]*/", ' ', $handleRep, $count);
In Ur For-Loop, what about refactoring the following lines:
line 2: $handles = trim($_POST['extract']);
through (trim is not necessary hier)
$handles = $_POST['extract'];
AND
line 11: $handleRep = strtolower(str_replace('#','',$handle));
through
$handleRep = trim(strtolower(str_replace('#','',$handle)));
Hey ;-),
U should also add some print_r(...) to debug each step
thanks #Ulrich Tevi Horus that made my code a bit cleaner but didn't solve the mysteriously disappearing users.
#shulard, you should post this as an answer to get the upvote. array_diff was indeed the best solution.
Here's the final code. Needs some tidying up but it's good enough to go on my server for testing.
//this is the current contents of the list:
$onlyHandles = array();
foreach ($organizedArray as $key2 => $val2) {
$onlyHandles[] = $val2['name'];
}
echo "<br>begin onlyhandles<br>";
print_r($onlyHandles);
echo "<br>end onlyhandles<br>";
//finish preparation for display
//if names submitted for the list list
if(!empty($_POST['extract'])){
$handles = trim($_POST['extract']);
$handles = explode("\n", $handles); //this is now an array
echo "<br>begin handles<br>";
print_r($handles);
echo "<br>end handles<br>";
//$countInput = count($handles);
if($countInput>200){
echo '<p style="color:red;">Please Enter fewer than 200 names!</p>';
exit(1);
}
else{
$handleFinal = array();
foreach($handles as $handle) {
//$handleRep = strtolower(str_replace('#','',$handle));
$handleRep = trim(strtolower(str_replace('#','',$handle)));
$handleClean = str_replace(str_split('\\/:*?&"<>=+ -#%$|'), 'p', $handleRep, $count);
//$handleClean = preg_replace("/\[\/:\*?&\"<>=\+-#%\$\|\s+\]*/", ' ', $handleRep, $count);
echo "handleClean: ".$handleClean."<br>";
if ($count > 0) {
echo '<p style="color:red;">Your input contained special characters.</p>';
exit(1);
}
else{
$handleFinal[] = $handleClean;
}
}//end foreach
}//finish checking count input number
echo "<br>begin handleFinal<br>";
print_r($handleFinal);
echo "<br>end handleFinal<br>";
$countFinal = count($handleFinal);
echo "<br>countfinal is ".$countFinal."<br>";
//check if this user is already in the list
$handleDiffs = array_diff($handleFinal,$onlyHandles);
echo "<br>begin handlediffs<br>";
print_r($handleDiffs);
echo "<br>end handlediffs<br>";
foreach($handleDiffs as $handleDiff) {
$sqlIns = "blah blah blah";
$resultIns = mysql_query($sqlIns);
$resInsArr[] = array($resultIns);
}
$countresIns = count($resInsArr);
if ($countresIns > 0){
$delmessage .= "<p>User(s) added to the list succesfully!</p>" ;
}
}
I post my comment answer as a real answer :)
You must trim your $handle variable too because it's possible to have some spaces around it...
Then about your problem, I don't understand it. Your code seems "clean", maybe you should consider set the strict flag to true see function definition here.
$file = fopen("test.txt","r");
while($line = fgets($file)) {
$line = trim($line);
list($model,$price) = preg_split('/\s+/',$line);
if(empty($price)) {
$price = 0;
}
$sql = "UPDATE products
SET products_price=$price
WHERE products_model='$model'";
// run the sql query.
}
fclose($file);
the txt file like this:
model price
LB2117 19.49
LB2381 25.99
1, what's the meaning of list($model,$price) = preg_split('/\s+/',$line);
i know preg_split like explode, but i don't know what't the parameter meaning of the above line
2, how to skip the first record.
it's taking the results of the preg_split and assigning them to the vars $model and $price. You're looking at a parsing algorithm. Sorry if this is not enough. I have a hard time understanding the question as it is written.
Also, if I read this correctly, there is no need to skip line 1 unless you have an item with the model defined as "model" in the database.
But if you wanted to for some reason, you could add a counter...
$i = 0;
while($line = fgets($file)) {
if($i > 0)
{
$line = trim($line);
list($model,$price) = preg_split('/\s+/',$line);
if(empty($price)) {
$price = 0;
}
$sql = "UPDATE products
SET products_price=$price
WHERE products_model='$model'";
// run the sql query.
}
$i++;
}
That is a language construct that allows you to assign to multiple variables at once. You can think of it as array unpacking (preg_split returns an array). So, when you do:
<?php
list($a, $b) = explode(".","a.b");
echo $a . "\n";
echo $b . "\n";
You will get:
a
b
Having less elements in list than the array is ok, excess elements in array are ignored, but having insufficent elements in array will give you an undefined index error. For example:
list($a) = explode(".","a.b"); // ok
list($a,$b,$c) = explode(".","a.b") // error
I don't know if you meant that by skip the first record but...
$file = fopen("test.txt","r"); // open file for reading
$first = true;
while($line = fgets($file)) { // get the content file
if ($first === true) { $first = false;}//skip the first record
else{
$line = trim($line); // remove the whitespace before and after the test
// not in the middle
list($model,$price) = preg_split('/\s+/',$line); // create two variable model and price, the values are from the preg_split \s means whitespace, tab and linebreak
if(empty($price)) { // if $price is empty price =0
$price = 0;
}
$sql = "UPDATE products // sql update
SET products_price=$price
WHERE products_model='$model'";
// run the sql query.
}
}
fclose($file); //close the file