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 "\"] })";
Related
This question already has answers here:
Implode a column of values from a two dimensional array [duplicate]
(3 answers)
Closed 7 months ago.
Ok, I know that to get a comma-seperated string from a string array in PHP you could do
$stringA = array("cat","dog","mouse");
$commaSeperatedS = join(',', $stringA);
But what if I have an array of arrays(not a simple string array)?
$myAssociativeA =
array(
[0] => array("type"=>"cat", "sex"=>"male")
, [1] => array("type"=>"dog", "sex"=>"male")
);
and my goal is to get a comma-seperated string from a specific property in each array, such as "type"? Ive tried
$myGoal = join(',', $myAssociativeA{'type'});
My target value for $myGoal in this case would be "cat,dog".
Is there a simple way without having to manually loop through each array, extract the property, then do a join at the end?
This should work for you:
(Here I just get the column which you want with array_column() and simply implode it with implode())
echo implode(",", array_column($myAssociativeA, "type"));
Another option is to use array_walk() to return the key you want:
array_walk($myAssociativeA, function(&$value, $key, $return) {
$value = $value[$return];
}, 'type');
echo implode(', ', $myAssociativeA); // cat, dog
Useful for older PHP versions - #Rizier123's answer using array_column() is great for PHP 5.5.0+
You can use this if you have PHP < 5.5.0 and >= 5.3.0 (thanks to #Rizier123) and you can't use array_column()
<?php
$myAssociativeA = array(array("type"=>"cat", "sex"=>"male"), array("type"=>"dog", "sex"=>"male"));
$myGoal = implode(',', array_map(function($n) {return $n['type'];}, $myAssociativeA));
echo $myGoal;
?>
EDIT: with the recommendation in the comment of #scrowler the code now is:
<?php
$myAssociativeA = array(array("type"=>"cat", "sex"=>"male"), array("type"=>"dog", "sex"=>"male"));
$column = 'type';
$myGoal = implode(',', array_map(function($n) use ($column) {return $n[$column];}, $myAssociativeA));
echo $myGoal;
?>
Output:
cat,dog
Read more about array_map in:
http://php.net/manual/en/function.array-map.php
You just have to loop over the array and generate the string yourself.
<?php
$prepend = '';
$out = '';
$myAssociativeA = array(
array('type' => 'cat'),
array('type' => 'dog')
);
foreach($myAssociativeA as $item) {
$out .= $prepend.$item['type'];
$prepend = ', ';
}
echo $out;
?>
You could easily turn this into a function.
<?php
function implode_child($array,$key) {
$prepend = '';
$out = '';
foreach($array as $item) {
$out .= $prepend.$item[$key];
$prepend = ', ';
}
return $out;
}
?>
Ok, under assumption that your assoc array fields are ordered always the same way you could use snippet like this. Yet you still need to iterate over the array.
$csvString = "";
foreach ( $myAssociativeA as $row ) {
$csvRow = implode(",", $row);
$csvString .= $csvRow . PHP_EOL;
}
Now if you don't want to store whole CSV in a variable (which you should not do) take a look at http://www.w3schools.com/php/func_filesystem_fputcsv.asp and see an example how to put it directly into the file.
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";
I'm trying to put an array into a query but I doens't work. I'm tying it with implode() but then it gives me " Array to string conversion in ... on line 26". Why? With json_encode it worked out ...
Thanks for your help!
$sql = mysql_query("SELECT follows
FROM follow
WHERE follower LIKE '".$id."'") or die (mysql_error());
if(mysql_num_rows($sql) < 1){
echo "<br/>";
echo "Follow someone";
} else {
//Put all the id's of the users the user is following in an array.
$i = 0;
$user_follows = array();
while ( $row = mysql_fetch_assoc($sql) )
{
$user_follows[$i] = $row;
$i++;
}
$user_follows = implode(" , ", $user_follows);
echo $user_follows;
}
The second argument to implode must be an array of strings. But you're doing:
$user_follows[$i] = $row;
Since $row is an array, you're making an array of arrays (a 2-dimensional array), not an array of strings. That should be:
$user_follows[] = $row['follows'];
You don't need the $i variable, assigning to $array[] appends a new element to the array.
I am printing a set of words that is placed in a MySQL database and I am retrieving it with PHP. I want to present it as a comma separated list, but I need it not to print or remove the last comma. How could I do this?
I did try to use rtrim, but I did not probably do it right.
This is my code as it is today:
<?php
$query0 = "SELECT LCASE(ord) FROM `keywords` ORDER BY RAND()";
$result0 = mysql_query($query0);
while($row0 = mysql_fetch_array($result0, MYSQL_ASSOC))
{
$keyword = $row0['LCASE(ord)'];
echo "$keyword, ";
?>
I did try to use rtrim, my attempt was something like this (I might be honest enough to say that I am in above my head in this ;) )
$keyword = $row0['LCASE(ord)'];
$keywordc = "$keyword, ";
$keyword- = rtrim($keywordc, ', ');
echo "$keyword-, ";
As you might imagine, this did not print much (but at least it did not leave me with a blank page...)
I would do:
$keywords = array();
while($row0 = mysql_fetch_array($result0, MYSQL_ASSOC))
{
$keywords[] = $row0['LCASE(ord)'];
}
echo implode(',', $keywords);
I usually do this by placing the results in an array first
$some_array = array();
while($row0 = mysql_fetch_array($result0, MYSQL_ASSOC)) {
$some_array[] = $row0['LCASE(ord)'];
}
then simply:
echo "My List: " . implode(', ', $some_array);
// Output looks something like:
My List: ord1, ord2, ord3, ord4
substr($string, 0, -1);
That removes the last character.
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'];
}