I have a string containing numbers separated by comma. ie, 1,2,3,6.... I have removed the comma using explode. Now i want to match the corresponding values in database.
My Code is,
$color = "1,2,3,9,5";
$color_split = explode(",", $color);
foreach($color_split as $item)
{
$select_color = "SELECT * FROM tbl_product_color WHERE color_id = '$item'";
$select_color_q = mysqli_query($c, $select_color) or die(mysqli_error($c));
$length = mysqli_num_rows($select_color_q);
if($length > 0)
{
while($select_color_r = mysqli_fetch_object($select_color_q))
{
$var[] = $select_color_r;
}
$var = json_encode($var);
echo '{"color_list":'.$var.'}';
}
else
{
$arr = array('status'=>"notfound");
echo '{"color_list":['.json_encode($arr).']}';
}
}
Now the output is,
{"color_list":[{"color_id":"1","color_name":"White","color_code":"#f2f2f2"}]}
and one error,
Fatal error: [] operator not supported for strings in C:\wamp\www\jithin\get_color.php on line 18
line 18 contains $var[] = $select_color_r;
My required output is,
{"color_list":[{"color_id":"1","color_name":"White","color_code":"#f2f2f2"},{"color_id":"2","color_name":"Black","color_code":"#000000"},{"color_id":"3","color_name":"Red","color_code":"#F000000"},...]}
You don't need to use foreach and explode over here you can simply update your MySql query and code like as
$color = "1,2,3,9,5";
$select_color = "SELECT * FROM tbl_product_color WHERE color_id IN ($color)";
$select_color_q = mysqli_query($c, $select_color) or die(mysqli_error($c));
$arr['color_list'] = array();
if(mysqli_num_rows($select_color_q) > 0)
{
while($select_color_r = mysqli_fetch_object($select_color_q))
{
$var[] = $select_color_r;
}
}else{
$var = array('status'=>"notfound");
}
$arr['color_list'] = $var;
echo json_encode($arr);
you set $var as string in here :
$var = json_encode($var);
but in the next step of foreach you want to use $var as array.
$var[] = $select_color_r;
just remove the following line :
$var = json_encode($var);
and change this line :
echo '{"color_list":'.$var.'}';
to
echo '{"color_list":'.json_encode($var);.'}';
Related
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 ']';
I just tried to create a spinner using MySQL and PHP, but after a few a hours it displays "ArrayArrayArray" in front of the expected output.
if($_POST['artikel']){
$artikel = nl2br($_POST['artikel']);
$ar = explode("\n\r",$artikel);
$hasil = "";
foreach($ar as $ars){
$newstring1 = explode(" ", $ars);
foreach($newstring1 as $newstring2){
$newstring3 = explode("\n", $newstring2);
foreach($newstring3 as $newstring4){
$newstring5 = explode(",", $newstring4);
foreach($newstring5 as $value){
$cari = mysql_query("select * from sinonim where kata1='$value'");
$j = mysql_num_rows($cari);
if($j>0){
$ka = mysql_fetch_array($cari);
$hasil = $hasil."<span class='re'>".$ka['kata2']." ";
$hasil = explode(",", $hasil);
foreach($hasil as $vv) {
$hasil = $hasil.$vv."</span> ";
}
}else{
$cari2 = mysql_query("select * from sinonim where kata2='$value'");
$j2 = mysql_num_rows($cari2);
if($j2>0){
$ka2 = mysql_fetch_array($cari2);
$hasil = $hasil."<span class='re'>".stripslashes($ka2['kata1'])."</span> ";
}else{
$hasil = $hasil.$value." ";
}
}
}
}
}
}
echo $hasil;
}
The result looks like this
ArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayhello all......
Why is "Array" printed? How can I avoid that?
Your code is a mess. The problem occurs in this part
$hasil = $hasil."<span class='re'>".$ka['kata2']." "; // line 1
$hasil = explode(",", $hasil); // line 2
foreach($hasil as $vv) { // line 3
$hasil = $hasil.$vv."</span> "; // line 4
} // line 5
In line 2 you use explode to split $hasil into an array, then in line 4 you try to append it to itself, although it's an array now not a string. This causes the "Array" output.
Eventually you want to use another variable here. Also you're adding multiple </span>, which will invalidate your HTML. I guess it should look like this:
$hasil = $hasil."<span class='re'>".$ka['kata2']." ";
$temp = explode(",", $hasil);
foreach($temp as $vv) {
$hasil = $hasil.$vv;
}
$hasil = $hasil."</span> ";
But line 4 still doesn't make sense. You're iterating over text tokens, which are already part of the output. What do you want to append here?
In your edit you stated that changing line 4 to $hasil = $vv."</span> "; solved your problem, but it looks like you're still producing invalid HTML and your code is way too complicated for what you're trying to achieve.
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);
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.
$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';