PHP min not working correctly - php

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);

Related

Create a list like array when echoed in php

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 ']';

how to make implode create <br /> automatic after displaying 5 things in a row?

I want to make implode to display only 5 arrays after that it automatic creates a new row displaying 5 arrays again and it keep repeating itself. like is it possible to use <br /> or something else I had to use to do that?
$result = mysql_query("SELECT * FROM `im_album` WHERE username = '".$user_data['username']."' ");
$types = array();
$d_array = array();
while(($row = mysql_fetch_assoc($result))) {
$types[] = $row['name'];
$d_array[] = $row['description'];
}
echo "<h1>".implode($types )."</h1>"
Try this one:
$result = mysql_query("SELECT * FROM `im_album` WHERE username = '".$user_data['username']."' ");
$types = array();
$d_array = array();
$types_str="";
$types_str_array=array();
$temp=1;
while(($row = mysql_fetch_assoc($result))) {
$types_str .=$row['name'];
if($temp!=1 && $temp%5==0)
{
$types_str_array[]=$types_str;
$types_str="";
}
$types[] = $row['name'];
$d_array[] = $row['description'];
$temp++;
}
echo "<h1>".implode("<br />",$types_str_array )."</h1>";
You could do something like this:
<?php
//sample array
$types = array("John", "Doe", "Bar", "Baz", "Stock", "Overflow", "Meta" );
//Count the number of elements in $types
$types_count = count($types);
//Use $foo1, $foo2, $foo3 as the output array names
$out_types_count = 1;
$out_types_arr = "foo".$out_types_count;
for($i=1;$i<=$types_count;$i++){
$out_types_arr[] = $types[$i];
if(($i%5) == 0){ // if we $i == 5,10,15 etc,
$out_types_count++; // use $foo2
$out_types_arr = "foo".$out_types_count;
}
}// for loop ENDS
//Echo all the output
for($i=1;$i<=$out_types_count;$i++){
for($j=0;$j<=5;$j++){
echo $out_types_arr.$i[$j];
}
echo "<br />".PHP_EOL;
}
?>
P.S. Code has some errors & minor not-desired output. Because OP has got the answer he wanted, so I am gonna correct it later, from home.

Proper PHP MYSQL array usage

I have not worked with arrays much in PHP. I have a table of colors. I want to load it into a multidimensional associative array because I am going to be using that table a lot and don't want to do selects over and over again.
I did:
$result = mysql_query("select * FROM color") or die(mysql_error());
$colors = "";
while($colorrec = mysql_fetch_array($result)){
$colors[$colorrec['ID']][0] = $colorrec['Description'];
$colors[$colorrec['ID']][1] = $colorrec['HexCode'];
}
then when I want to access a colors information, I can just do something like:
echo "color code WHT";
echo "description ".$colors['WHT'][0];
echo "Hex Code ".$colors['WHT'][1];
Is this the correct way/methodology to do this?
$colors = ""; //what?? this should be array()
This should be something like:
$result = mysql_query("select * FROM color") or die(mysql_error());
$colors = array();
while($colorrec = mysql_fetch_array($result)){
$colors[$colorrec['ID']] = array();
$colors[$colorrec['ID']]['Desc'] = $colorrec['Description'];
$colors[$colorrec['ID']]['Hex'] = $colorrec['HexCode'];
}
Then you can do:
echo "color code WHT";
echo "description ".$colors['WHT']['Desc'];
echo "Hex Code ".$colors['WHT']['Hex'];
Sure nothing wrong with going this way. Also if you get lost in your array, just do a quick print_r($array) and it will output the structure for you.
try with:
$result = mysql_query("select * FROM color") or die(mysql_error());
$colors = array();
while($colorrec = mysql_fetch_array($result)){
$colors[$colorrec['ID']] = array(
$colorrec['Description'] ,
$colorrec['HexCode'] );
}
echo "color code WHT";
echo "description ".$colors['WHT'][0];
echo "Hex Code ".$colors['WHT'][1];
Neal you can do as he mentioned, if you want more clean go OOP (PHP5)
class Color
{
$description ="";
$hexcode = "";
$someOther="";
}
$colors = array();
$result = mysql_query("select * FROM color") or die(mysql_error());
while($colorrec = mysql_fetch_array($result))
{
$color = new Color();
$id=$colorrec['HexCode'];
$color->description = $colorrec['Description'];
$color->hexCode = $colorrec['HexCode'];
$colors[$id] = $color;
}
echo $color['ID']->description;
echo $color['ID']->hexCode;
I use it like this:
$numfields = mysql_num_fields($result);
while($red = mysql_fetch_array($result)){
for ($j=0; $j<$numfields; $j++ ) {
$field_name = mysql_field_name($result, $j);
//create Matrix
$datapull[$i][$field_name] = $red[$field_name];
}
$i++;
}
mysql_free_result($result);
var_dump($datapull);
This is more generic and harder to search, it should be used in class method or a function, so you pass the SQL and always expect the same format as a result.

format mysql data in array

I am pulling data from my database and trying to encode into JSON data using json_encode. But to make it easier to read in my android app. I was hopping to format it differently then I am currently doing. Please see bottom encode string example. Any help would be great. Thanks in Advance.
$result = $db->query($query);
while($info = mysql_fetch_array($result))
{
$content[] = $info;
}
$count = count($content);
$result=array();
for($i=0;$i<$count;$i++)
{
$result[id][] = $content[$i]['imageID'];
$result[name][] = $content[$i]['Name'];
$result[thumb][] = $content[$i]['Thumb'];
$result[path][] = $content[$i]['Path'];
}
echo json_encode($result);
{"id":["1","2","3"],"name":["Dragon","fly","bug"],"thumb":["thm_polaroid.jpg","thm_default.jpg","thm_enhanced-buzz-9667-1270841394-4.jpg"],"path":["polaroid.jpg","default.jpg","enhanced-buzz-9667-1270841394-4.jpg"]}
But I am trying to format my array like so when it is encoded by json_encode.
[{"id":"1","name":"Dragon","thumb":"thm_polaroid.jpg","path":"polaroid.jpg"},{"id":"2","name":"Fly","thumb":"thm_default.jpg","path":"default.jpg"},{"id":"3","name":"Bug","thumb":"thm_enhanced-buzz-9667-1270841394-4.jpg","path":"enhanced-buzz-9667-1270841394-4.jpg"}]
Well, there is a problem. This is not valid JSON:
{"image":["1","Dragon","thm_polaroid.jpg","polaroid.jpg"],
"image":["2","fly","thm_default.jpg","default.jpg"]}
A JSON object can only have one value per unique key. This means that your latter image key would clobber the value of the former.
If you are content with this, however:
[["1","Dragon","thm_polaroid.jpg","polaroid.jpg"],
["2","fly","thm_default.jpg","default.jpg"]]
Then you can simply use mysql_fetch_row:
$result = $db->query($query);
while($info = mysql_fetch_row($result))
{
$content[] = $info;
}
echo json_encode($content);
Side Note:
Generally, in PHP, it is best to use foreach( $arr as $val ) (or $arr as $key => $val). for loops should be limited to when they are strictly necessary.
You need to add the iterator $i to the setting array
for($i=0;$i<$count;$i++)
{
$result[$i][id] = $content[$i]['imageID'];
$result[$i][name] = $content[$i]['Name'];
$result[$i][thumb] = $content[$i]['Thumb'];
$result[$i][path] = $content[$i]['Path'];
}
<?
$result = $db->query($query);
while($info = mysql_fetch_array($result))
$content[] = $info;
$result=array();
$count = count($content);
for ($x=0;$x<$count;++$x)
{
$result[$x][] = $content[$x]['imageID'];
$result[$x][] = $content[$x]['Name'];
$result[$x][] = $content[$x]['Thumb'];
$result[$x][] = $content[$x]['Path'];
}
echo json_encode($result);
?>

php string name as variable

$string = "id";
want result to be like
$id = "new value";
How do I code this in php?
Edit..
How about the below?
$column = array("id","name","value");
let say found 3 row from mysql
want result to be like this
$id[0] = "3";
$id[1] = "6";
$id[2] = "10";
$name[0] = "a";
$name[1] = "b";
$name[2] = "c";
$value[0] = "bat";
$value[1] = "rat";
$value[2] = "cat";
Theres 2 main methods
The first is the double $ (Variable Variable) like so
$var = "hello";
$$var = "world";
echo $hello; //world
//You can even add more Dollar Signs
$Bar = "a";
$Foo = "Bar";
$World = "Foo";
$Hello = "World";
$a = "Hello";
$a; //Returns Hello
$$a; //Returns World
$$$a; //Returns Foo
$$$$a; //Returns Bar
$$$$$a; //Returns a
$$$$$$a; //Returns Hello
$$$$$$$a; //Returns World
//... and so on ...//
#source
And the second method is to use the {} lik so
$var = "hello";
${$var} = "world";
echo $hello;
You can also do:
${"this is a test"} = "works";
echo ${"this is a test"}; //Works
I had a play about with this on streamline objects a few weeks back and got some interesting results
$Database->Select->{"user id"}->From->Users->Where->User_id($id)->And->{"something > 23"};
You are looking for Variable Variables
$$string = "new value";
will let you call
echo $id; // new value
Later in your script
Second answer in response to your edit:
$result = mysql_query($sql);
$num = mysql_num_rows($result);
$i = 0;
$id = array();
$name = array();
$value = array();
if ($num > 0) {
while ($row = mysql_fetch_assoc($result)) {
$id[$i] = $row['id'];
$name[$i] = $row['name'];
$value[$i] = $row['value'];
$i++;
}
}
This loops around your result, using the counter $i as the key for your result arrays.
EDIT
Additional answer in response to your comment:
while ($row = mysql_fetch_assoc($result)) {
foreach($row as $column_name => $column_value) {
$temp_array[$column_name][$i] = $column_value;
}
$i++;
}
foreach ($temp_array as $name => $answer) {
$$name = $answer;
}
This code creates a temporary multidimensional array to hold the column names and values the loops around that array to create your variable variable arrays. As a side not I had to use the temp array as $$column_name[$i] doesn't work, I would love to see alternative answers to this problem.
Final note #Paisal, I see you have never accepted an answer, I wouldn't have put this much effort in if I had seen that before!
You can do this
$$string = "new value";
juste double $
Are you referring to variable variables?
That would accomplish something like this:
$string = "id";
$$string = "new value";
This produces a variable $id with the value "new value".
Don't do that. Just use an array.
$arr[$string] = 'new value';
ref: How do I build a dynamic variable with PHP?
Try this :
$result = mysql_query($sql);
$num_rows = mysql_num_rows($result);
$i = 0;
if ($num_rows) {
while ($row = mysql_fetch_assoc($result)) {
foreach($row AS $key => $value) {
${$key}[$i] = $value;
}
$i++;
}
}
For those of us who need things explained in great detail...
// Creates a variable named '$String_Variable' and fills it with the string value 'id'
$String_Variable = 'id';
// Converts the string contents of '$String_Variable', which is 'id',
// to the variable '$id', and fills it with the string 'TEST'
$$String_Variable = 'TEST';
// Outputs: TEST
echo $id;
// Now you have created a variable named '$id' from the string of '$String_Variable'
// Essentially: $id = 'Test';

Categories