I would like to echo my results from a database and have them look like an array. They don't necessarily have to be an array but look like one. i.e. When i echo my result,
i would want my final result to look like
[10,200,235,390,290,250,250]
When i try the code below:
$query_rg = mysqli_query($link, "SELECT column FROM `table`");
$row_rg = mysqli_fetch_assoc($query_rg);
echo '[';
while ($row = mysqli_fetch_assoc($query_rg)) {
$list = $row['column'];
$listwithcoma = "$list,";
echo ltrim($listwithcoma,',');
}
echo ']'
The result is :
[10,200,235,390,290,250,250,]
You are doing it wrong. ltrim($listwithcoma,',') has no effect.
ltrim — Strip whitespace (or other characters) from the beginning of a string
You can try a simple way with implode.
$list = array();
while ($row = mysqli_fetch_assoc($query_rg)) {
$list[] = $row['column'];
}
echo '[' . implode(',', $list) . ']';
Just use GROUP_CONCAT in query as
$query_rg = mysqli_query($link, "SELECT GROUP_CONCAT(`column` SEPARATOR ', ') as data
FROM `table`");
$row_rg = mysqli_fetch_assoc($query_rg);
print_r($row_rg['data']);
Try like this
$list = array(); //define a array.
while ($row = mysqli_fetch_assoc($query_rg)) {
$list[] = $row['column']; //store column value in array.
}
$lists = "[".implode(",",$list)."]";
echo $lists; //will echo your results.
You should be using rtrim() function instead, that too outside the loop.
$listwithcoma = '';
echo '[';
while ($row = mysqli_fetch_assoc($query_rg)) {
$list = $row['column'];
$listwithcoma .= "$list,";
// echo ltrim($listwithcoma,','); Remove this
}
echo rtrim($listwithcoma,','); // Add this
echo ']';
Related
$result = mysqli_query($con, "SELECT * FROM users");
$usersArray=[];
tableArrayPushData($result, $usersArray);
function tableArrayPushData($result, $tableArray){
while ($row = $result->fetch_assoc()) {
$str = '';
foreach ($row as $value) {
$str = $str.$value.'|';
}
$newStr = rtrim($str, "| ");
array_push($tableArray,$newStr);
}
}
for ($i=0; $i<count($usersArray); $i++){//array is always empty at this point
echo "Ok";
echo "<br>";
}
I don't understand why, but usersArray is empty despite the fact that I added data there.
The MySQL table has rows with data, so it can't be empty.
You should use the & operator to allow the function to access the outer variable, like this:
function tableArrayPushData($result, &$tableArray) {}
Or use return.
I cannot solve this seeming simple problem. I have the following simple code and all I want is to echo the result of $ATL5_Alert_query and separated by a comma (,):
$ATL5_Alert_query = mysql_query("SELECT `Mobile` FROM `dbo_tech_name` WHERE `AlertLevel`= 1");
$dataset = array();
while ($data = mysql_fetch_array($ATL5_Alert_query))
{
$dataset[] = $data;
}
echo implode (",", $dataset);
However, I'm getting "Notice: Array to string conversion "...
In your code $data is array as well, so $dataset becomes an array of arrays, which you cannot concatenate. You should get the searched value by this:
while ($data = mysql_fetch_array($ATL5_Alert_query))
{
$dataset[] = $data['Mobile'];
}
or:
while ($data = mysql_fetch_array($ATL5_Alert_query))
{
$dataset[] = $data[0];
}
or:
while ($data = mysql_fetch_assoc($ATL5_Alert_query))
{
$dataset[] = $data['Mobile'];
}
If you however cannot change this, and already have your $dataset array, you can implode it like that:
echo implode(',', array_map(function($a){
return $a['Mobile'];
},$dataset));
I have an array with 3 values(56.767, 360.997, 579.728). These are in an array($distance).
Well, when I run the min($distance) I get '360.997'. What gives?
<?php
include('mysql_connect.php');
$MasterState = 'CA';
$query = 'select * from estes_term where Dest_State = "'.$MasterState.'"';
$result = mysql_query($query);
if($result) {
$row = #mysqli_fetch_row($result);
}
$Term_Zip = array();
$Distance = array();
$i = '0';
while ($row = mysql_fetch_array($result, MYSQLI_ASSOC)) {
$Term_Zip[] = $row['Term_Zip'];
$Distance_xml = file_get_contents('http://zipcodedistanceapi.redline13.com/rest/ua6z0ep0djB3zHGz5Z40hONMVc8yuXgY8nx8BX8OhKSRrzqxzvyRjmDeyMM3J32S/distance.xml/90077/'.$Term_Zip[$i].'/mile');
$Distance[] = $Distance_xml;
$i++;
}
echo '<pre>';
var_dump($Term_Zip);
var_dump($Distance).'<br />';
$test1 = min($Distance);
$test = (array_keys($Distance, min($Distance)));
echo '<br />';
echo 'Min'.min($Distance);
?>
As #Rocket pointed out, your variables are stored as strings, not floats. This, the character "3" is smaller than "5", so it's the first one. To avoid this use Type Juggling or floatval() in your code to assure your vars are float as:
$Distance[] = floatval(trim($Distance_xml));
Do like this... We are converting all the array elements to float using array_map and then finding the min value from it.
<?php
$arr= array(56.767, 360.997, 579.728);
echo min(array_map('floatval',$arr));
OUTPUT :
56.767
EDIT :
To get the key , you can make use of array_search()
$key = array_search(min(array_map('floatval',$arr)), $arr);
Can't find quite the right answer so hope someone can help. Basically want to create an array and then return the results from a search e.g.
$tsql = "SELECT date, staffid, ID,status, eventid, auditid from maincalendar";
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt = sqlsrv_query( $conn, $tsql , $params, $options);
$calarray=array();
while($row = sqlsrv_fetch_array($stmt)) {
$rowresult = array();
$rowresult["status"] = $row['status'];
$rowresult["eventid"] = $row['eventid'];
$rowresult["caldate"] = $row['date'];
$rowresult["staffid"] = $row['staffid'];
$rowresult["ID"] = $row['ID'];
$rowresult["auditid"] = $row['auditid'];
$calarray[] = $rowresult;
}
I would then like to search for values matching 'caldate' and 'staffid' and return the associated entry in $calarray
I suggest the following,
Fetch all data needed for the current month you are showing, using col BETWEEN x AND y
Add them to a array in PHP, with staffid and caldate as key
Something like so;
$calarray[$row['staffid'] . '-' . $row['date']][] = $row;
Not sure if a single staffid/date combination can have one or more events per day, if not you can remove the []
To check if we have information for a specific staffid/date combination, use isset
if (isset($calarray[$staffid . '-' . $mydate]) { ... }
Add indexes to the fields you're going to query, and then move the search to the sql query. You can also make simple filtering inside the loop. So you'll be populating several arrays instead of one, based on the search you need.
try this:
$matches = array();
$caldate = //your desired date;
$staffid = //your desired id;
foreach($calarray as $k => $v){
if(in_array($caldate, $v['caldate']) && in_array($staffid, $v['staffid'])){
$matches[] = $calarray[$k];
}
}
$matches should be and array with all the results you wanted.
also:
while($row = sqlsrv_fetch_array($stmt)) {
$rowresult = array();
$rowresult["status"] = $row['status'];
$rowresult["eventid"] = $row['eventid'];
$rowresult["caldate"] = $row['date'];
$rowresult["staffid"] = $row['staffid'];
$rowresult["ID"] = $row['ID'];
$rowresult["auditid"] = $row['auditid'];
$calarray[] = $rowresult;
}
can be shortened into:
while($row = sqlsrv_fetch_array($stmt)) {
$calarray[] = $row;
}
Maybe this code snipplet solves your problem.
I am not a PHP programmer, so no warrenty.
function searchInArray($array, $keyword) {
for($i=0;$i<array.length();$i++) {
if(stristr($array[$i], $keyword) === FALSE) {
return "Found ".$keyword." in array[".$i."]";
}
}
}
Hi I currently have this code that retrieves the tags from each Image in the Database. The tags are seperated by commas. I place each set of tags on the end of the array. Now I want to create an array of the tags retrieved but merge any duplications.
function get_tags()
{
$tag_array = array();
$query = mysql_query("
SELECT tags
FROM gallery_image
");
while($row = mysql_fetch_assoc($query))
{
$tags = $row['tags'];
$tag_array[] = $tags;
}
echo $tag_array[0] . '<br>' . $tag_array[1] . '<br>' .$tag_array[2];
}
You question is not very clear but array_unique may be what you need?
function get_tags()
{
$query = mysql_query('SELECT tags '.
'FROM gallery_image');
$tag_array = array();
while($row = mysql_fetch_assoc($query))
$tag_array = array_merge($tag_array, explode(',', $row['tags']));
return array_unique($tag_array);
}
You probably want something like this:
$tags = array(
'one,two',
'one,three',
);
$result = array_unique(array_reduce($tags,
function($curr, $el) {
return array_merge($curr, explode(',', $el));
},
array()));
See it in action.
What this does is process each result row (which I assume looks like "tag1,tag2") in turn with array_reduce, splitting the tags out with explode and collecting them into an intermediate array which has just one tag per element. Then the duplicate tags are filtered out with array_unique to produce the end result.
Try this:
$unique_tags = array();
foreach ($tag_array as $value) {
$unique_tags = array_merge($unique_tags, explode(",", $value);
}
$unique_tags = array_unique($unique_tags);