Exploding an array for an email message - php

I am attempting to generate a weekly email to users of my site that lists locations that have added new information. When someone adds information, a table receives two numbers, one for the state and the second for the county. The first step of my cron job is to take the numbers and convert them to county, state format (Alameda, California for example). At the end of each conversion I added a | to be used as a delimiter. This part works perfectly. Next I loop through each user to send this information via email but this part does not work. What I end up with is the word array instead of my county, state format. What am I missing?
This is the code that performs the 1st step, which works just fine:
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
$SID = $row['SID'];
$CID = $row['CID'];
$states = mysql_query("SELECT * FROM State WHERE ID = '$SID'");
while ($state = mysql_fetch_array($states)) {
$statename = $state['Name'];
}
$countys = mysql_query("SELECT * FROM County WHERE ID = '$CID'");
while ($county = mysql_fetch_array($countys)) {
$countyname = $county['Name'];
}
$locations = '<a href="http://hammerpins.net/display.php?state=' . $SID .' &county=' . $CID .'" >' . "$countyname, $statename ". '</a>' . "|";
$i = $i + 1;
}
This is the code that I am using to explode the array into the county, state format, which does not function properly. Instead I get the word array.
$locals = explode("|", $locations);
$locals is used in the email message as the list of new information. Please point me in the right direction. Thanks

explode will give you array
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
so when you use explode function, it will explode string in to array
in your case .. write
$locals = explode("|", $locations);
echo "<pre>";print_r($locals);echo "</pre>";
and you will have exact idea and it will solve your problem

First, what is the purpose of $i?
Second, I think you want to concatenate $locations:
// This overwrites the variable - this is what you are doing
// at the end $locations will be the one single last link
$locations = '<a href="ht
// This adds to / concatenates - giving you a long strong of many links
$locations .= '<a href="ht
// ^ Note the period.
Third, explode does take a string and turns it into an array.
If you're making a long string, why would you want to explode it back into the parts you constructed it from?
I would suggest storing your states, countys, and constructed links in arrays. Then you can use the contents of those arrays at will to create your emails.
To look at what's in an array use print_r() or var_dump(). You can loop over arrays with foreach().
<?php
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
$SID = $row['SID'];
$CID = $row['CID'];
$states = mysql_query("SELECT * FROM State WHERE ID = '$SID'");
while ($state = mysql_fetch_array($states)) {
// There had better only be ONE statename per SID or you lose info!
$user_array[$i]['statename'] = $state['Name'];
}
$countys = mysql_query("SELECT * FROM County WHERE ID = '$CID'");
while ($county = mysql_fetch_array($countys)) {
// There had better only be ONE countyname per CID or you lose info!
$user_array[$i]['countyname'] = $county['Name'];
}
$user_array[$i]['link'] = '<a href="http://hammerpins.net/display.php?state=' . $SID .' &county=' . $CID .'" >' . "{$user_array[$i]['countyname']}, {$user_array[$i]['statename']} ". '</a>';
++$i; // add one to i
}
// Show the arrays:
echo "<pre>";
print_r($user_array);
echo "</pre>";
?>
The above gives you an array like
Array
(
[0] => Array
(
[statename] => CA
[countyname] => San Bernardino
[link] => <a href="blah...
)
[1] => Array
(
[statename] => OR
[countyname] => Multnomah
[link] => <a href="yada...
)
)
To use the array just do
foreach ($user_array as $single_user_item) {
echo $single_user_item['link'];
}

Related

php variable based on a random variable

I'm new to php and I wrote a code that takes a random winner out of an array and displays it, then I wanted to try to display all the names without the winner's, but how can I unset the winner by using the random number generated? I managed to unset a random name but not the same as the winner...
<?php
// array
$winner = array();
array_push($winner,"sonia");
array_push($winner,"ice");
array_push($winner,"sasha");
array_push($winner,"isa");
array_push($winner,"omar");
array_push($winner,"anwar");
// random winner
$giocatori = count($winner);
$random = rand(0,$giocatori -1);
unset($winner[$random]);
// Sort the list
sort($winner);
echo "I giocatori sono: ";
print join(", ",$winner);
// Print the winner's name in ALL CAPS
$truewinner = strtoupper($winner[$random]);
echo "<br><br>";
echo "il vincitore è: ";
// Print winner + sentence
$losers = "losers";
$losers = strtoupper($losers);
echo (strtoupper($winner[$random]));
echo "<br><br>";
echo "all the players are: $losers beside $truewinner";
?>
$players = array('sonia', 'ice', 'sasha', 'isa', 'omar');
$random = rand(0, count($players) - 1);
$winner = $players[$random];
$losers = array_diff($players, array($winner));
echo 'All players are: ' . implode(', ', $players);
echo 'Winner is: ' . $winner;
echo 'Losers are: ' . implode(', ', $losers);
How to write the array:
$participants = array("sonia", "ice", "sasha","isa","omar","anwar");
or
$participants = array();
$participants[] = "sonia";
$participants[] = "ice";
and soo on
//make all participants name first letter uppercase
$participants = array_map(function($string) {return ucfirst($string);},$participants);
To get an random value from the array you have:
//get a random key
$random = array_rand($participants);
//get the value for the key
$winner = $participants[$random];
//unset the key and value
unset($participants[$random]);
OR
//this will shuffle values in the array on random positions
shuffle($participants);
//this return the last value from the array and deletes it from the array
$winner = array_pop($participants);
echo "The winner is $winner !\n";
echo "The losers are ".implode(', ',$participants)."\n";
<?php
// array
$winner = array();
array_push($winner,"sonia");
array_push($winner,"ice");
array_push($winner,"sasha");
array_push($winner,"isa");
array_push($winner,"omar");
array_push($winner,"anwar");
// random winner
$giocatori = count($winner);
$random = rand(0,$giocatori -1);
echo "winner is".$winner[$random];
unset($winner[$random]);
// Sort the list
sort($winner);
echo print_r($winner) ;
echo "losers are ";
foreach($winner as $res) {
echo $res. ' ';
}
?>
Output
winner is anwar
Array
(
[0] => ice
[1] => isa
[2] => omar
[3] => sasha
[4] => sonia
)
losers are ice isa omar sasha sonia

Compare two strings and generate a new string with components from both

I have a sting that looks like this
$storelist = "‘F Mart (6)’, ‘ACME (5)’, 'J/M Store (17)'";
I want to break out selected companies and the number of locations by comparing the first string to a second string like
$selectedstores = "‘F Mart’, 'J/M Store";
And output a sting like
$selectedwithnumber = "‘F Mart (6)’, 'J/M Store (17)'"
There could be 1 to 15 companies in a string and the location number varies but the apostrophes and parenthesis are standard. I hope there an easy way to do this as I have no idea where to start. Thanks in advance.
You can use explode function to split arrays to parts, and use preg_replace function to remove number of companies (with brackets) from first string. below you can find working example:
$storelist = "‘F Mart (6)’, ‘ACME (5)’, 'J/M Store (17)'";
$selectedstores = "‘F Mart’, 'J/M Store'";
//split second array
$selectedArray = explode(', ', $selectedstores);
$resultArray = array();
//split first array
foreach(explode(', ', $storelist) as $storeWithNumber) {
//remove " (number)" from each part
$store = preg_replace('/\s+\(\d+\)/', '', $storeWithNumber);
//check if current part is on selected list
if (in_array($store, $selectedArray)) {
$resultArray[] = $storeWithNumber;
}
}
$selectedwithnumber = implode(', ', $resultArray);
echo $selectedwithnumber.PHP_EOL;
result is:
‘F Mart (6)’, 'J/M Store (17)'
This will get what you need based on your description. It breaks up your strings into arrays and then uses a nested foreach loop to do the comparisons. I used string functions over regular expression functions in case speed becomes an issue. It does however require that your main string of stores follows the conventions you described.
<?php
$storelist = "'F Mart (6)', 'ACME (5)', 'J/M Store (17)'";
$selectedstores = "'F Mart', 'J/M Store'";
$stores = explode(",", $storelist);
$selected = explode(",", $selectedstores);
$newStoreList = array();
foreach($selected as $selectedStore) {
foreach($stores as $store) {
$s = trim( $selectedStore, "' ");
if(strstr($store, $s)) {
$newStoreList[] = $store;
}
}
}
$newStoreList = implode(",", $newStoreList);
echo $newStoreList;
?>
This will output: 'F Mart (6)', 'J/M Store (17)'
Hope that helps!

PHP how to output the top array_count_values value from array?

I have a table that I need to find "top trusted builder" from, Trusts are separated by " ; ", So I need to pull all the data, explode the usernames, order and count them, and Im stuck on finally outputting the top username form the array, I have posted up the full segment of PHP, because im sure there has to be a much better way of doing this.
<?php
$GTB = $DBH->query('SELECT builders from griefprevention_claimdata where builders <> ""');
$GMCB->setFetchMode(PDO::FETCH_ASSOC);
$buildersarray = array();
while($row = $GTB->fetch()) {
$allbuilders = explode(";", $row['builders']);
for($i = 0; $i < count($allbuilders); $i++)
{
$buildersarray[] = $allbuilders[$i];
}
}
echo "<pre>";
print_r(array_count_values(array_filter($buildersarray)));
echo "</pre>";
?>
Outputs
Array
(
[username1] => 4
[username2] => 1
[username3] => 1
)
You can return the array from the array_count_values command into a new array called $topbuilders, and then echo out the current (first) record:
$topbuilders = array_count_values(array_filter($buildersarray));
echo current(array_keys($topbuilders)).', Rank = '.current($topbuilders);
current() will return the first item in an associative array.
Instead of using array_count_values() it would be better to use the names as the key to a frequency array:
$GTB = $DBH->query('SELECT builders from griefprevention_claimdata where builders <> ""');
$result = array();
while (($builders = $GTB->fetchColumn()) !== false) {
foreach (explode(";", $builders) as $builder) {
if (isset($result[$builder])) {
$result[$builder]++;
} else {
$result[$builder] = 1;
}
}
// sort descending based on numeric comparison
arsort($result, SORT_NUMERIC);
echo "Name = ", key($result), " Count = ", current($result), "\n";

generating a set of javascript code using php

I´m trying using php to generate a set of "{URL.callback}" to use in javascript. By using database. Here is my code:
$sql="select * from search where keywords LIKE '$bb%' ORDER BY keywords ";
$result=mysql_db_query($dbname,$sql);
echo $_GET["callback"] . "({ t:\"$t\", r:[";
while ( $rs=mysql_fetch_array($result)) {
$keywords=$rs[keywords];
echo "" ."\"$keywords\"".","." ";
}
echo"] })";
This is the code it returns:
({ t:"", r:["example1", "example2", "example3",] })
Everything seemed to be correct except the (,) in the end (after "example3") that I want to get rid. because it´s not correct and can not be use with that.
The question is: How to generate it correctly ? How to get rid the last (,) ?
Instead of generating the JSON yourself use json_encode to do the heavy lifting for you.
$keywords = array ();
while ( $rs=mysql_fetch_array($result)) {
$keywords[] = $rs['keywords'];
}
echo json_encode ($keywords);
Preferred solution
Though if you plan on using json_encode append $keywords to your other set of data and use json_encode on the whole structure.
$json_data = array (
't' => '',
'r' => array ()
);
while ( $rs=mysql_fetch_array($result)) {
$json_data['r'][] = $rs['keywords'];
}
echo "(".json_encode ($json_data).")";
If you'd like to do it yourself there are a few (rather clean) options available, see the snippets below.
Append all retrieved keywords to an array and use join with ',' as delimiter to form a string after your while loop
 
$keyword_array = array ();
while ($rs=mysql_fetch_array($result)) {
$keywords=$rs[keywords];
$keyword_array = "\"$keywords\"";
}
echo join (', ', $keywords);
Use mysql_num_rows before your while loop to get the number of rows in $result, and don't append a , when you are processing the last element.
$n_rows = mysql_num_rows ($result);
for ($i =1; $rs = mysql_fetch_array ($result); ++$i) {
$keywords=$rs[keywords];
echo "\"$keywords\"";
if ($i != $n_rows)
echo ", ";
}
Try this:
$output = '';
while ( $rs=mysql_fetch_array($result)) {
$keywords=$rs[keywords];
$output .= "" ."\"$keywords\"".","." ";
}
$output = substr($output, 0, -2);
echo $output;
Solution
Create data structure (multi-dimensional array) within PHP and let json_encode() generate JS data structure.
Example
It could look like this:
$sql="select * from search where keywords LIKE '$bb%' ORDER BY keywords ";
$result=mysql_db_query($dbname,$sql);
$data = array(
't' => $t,
'r' => array(),
);
while ( $rs=mysql_fetch_array($result)) {
$data['r'][] = $rs['keywords'];
};
and then display it like that:
echo $_GET["callback"].'('.json_encode($data).');';
Hope this works for you
$sql="select * from search where keywords LIKE '$bb%' ORDER BY keywords ";
$result=mysql_db_query($dbname,$sql);
echo $_GET["callback"] . "({ t:\"$t\", r:[";
$keywords_print = array();
while ( $rs=mysql_fetch_array($result)) {
$keywords=$rs[keywords];
$keywords_print[] = "\"$keywords\"";
}
echo implode(",",$keywords_print);
echo"] })";
I think the cleanest way, is to create an array of elements, then implode them with a , as separator.
// added initial `"`
echo $_GET["callback"] . "({ t:\"$t\", r:[\"";
while ( $rs=mysql_fetch_array($result)) {
$keywords=$rs[keywords];
$arr[] = $keywords;
}
echo implode('", "', $arr);
// added closing `"`
echo "\"] })";

associative array pointers / traversing associative array

Does next() and prev() work on associative arrays?
I'm trying to traverse through a dataset that uses two records to describe one "game" if you will. So when I'm on the second record w/ matching id i need to look at the record before and grab eg_item['final_score'].
{"id":"75", "team_name":"TEAM1", "home_team_name":"TEAM1", "image":"TEAM1_HOME.png", "final_score":"37"},
{"id":"75", "team_name":"TEAM2", "home_team_name":"TEAM2", "image":"TEAM2_AWAY.png", "final_score":"10"},
{"id":"76", "team_name":"TEAM1", "home_team_name":"TEAM1", "image":"TEAM1_HOME.png", "final_score":"10"},
{"id":"76", "team_name":"TEAM2", "home_team_name":"TEAM2", "image":"TEAM2_AWAY.png", "final_score":"14"},
All of the examples I'm finding use lame array('one','two',three') type examples that just don't help.
code sample:
foreach( $json_output as $eg_item ) :
if( $this_game_id == $last_game_id ) :
// get this records info
$b_score = $eg_item['final_score'];
$b_team_name = $eg_item['team_name'];
prev( $json_output );
// get previous records info
$a_score = $eg_item['final_score'];
$a_team_name = $eg_item['team_name'];
$a_game_id = $eg_item['id'];
// put pointer back
next( $json_output );
else :
// skip next record
endif;
endforeach;
That looks like an array of associative arrays, right? If so, loop through them by index 2 at a time, then you can look at the current inner array and the previous inner array in each iteration of the loop:
for ($i = 1; $i < count($array); $i+= 2) {
$current = $array[$i];
$last = $array[$i-1];
//$current['final_score'], $last['final_score'], etc
}
Yes they work just fine, heres a small test case i have done:
<?php
$sample = array(
"first" => Array("a","d","c"),
"second" => Array("a","d","c"),
"third" => Array("a","d","c"),
"fourth" => Array("a","d","c")
);
while(next($sample))
{
$item = current($sample);
echo key($sample) . "\n";
if(is_array($item))
{
echo "\t" . current($item) . "\n";
while(next($item))
{
echo "\t" . current($item) . "\n";
}
}
}
?>
output: http://codepad.org/2ZeqzWcx

Categories