how to store associative array php MySQL - php

I want to store result of a query as associative array. Below is my code that generates the query result below.
<?php
$include('config.php') //mysql connection file
$result = mysql_query("SELECT daystime.*, Sprinkler_ID FROM daystime, scheduler WHERE daystime.id = scheduler.DaysTime_ID ORDER BY daystime.id, Sprinkler_ID") or trigger_error(mysql_error());
$data_array = array();
while($rs = mysql_fetch_assoc($result))
{
$key=$rs['id'];
$value=$rs['Sprinkler_ID'];
$data_array[$key] = [$value];
}
foreach ($data_array as $key => $value)
{
echo $key.'=>'.$value.'<br />';
}
?>
This gives me output as
19=>Array
20=>Array
21=>Array
27=>Array
29=>Array
But I should get
19 -> [4,5],
20 -> [5],
21=>[4,6],
// and so on

$value is an array, you can't use echo on arrays
Don't loop just do a var_dump()
$data_array = array();
while($rs = mysql_fetch_assoc($result)){
$data_array[$rs['id']][]=$rs['Sprinkler_ID'];
}
var_dump($data_array);//or print_r($data_array);

<?php
$include('config.php') //mysql connection file
$result = mysql_query("SELECT daystime.*, Sprinkler_ID FROM daystime, scheduler WHERE daystime.id = scheduler.DaysTime_ID ORDER BY daystime.id, Sprinkler_ID") or trigger_error(mysql_error());
$data_array = array();
while($rs = mysql_fetch_assoc($result))
{
$key=$rs['id'];
$value=$rs['Sprinkler_ID'];
$data_array[$key] = [$value];
}
$out = '';
$count = count($data_array);
$iter = 0;
foreach ($data_array as $key => $value)
{
$out.= $key.'=>[';
foreach ($value as $val) {
$out.=$val.',';
}
$out = rtrim($out, ",");
$out.= ']';
if ($iter < ($count-1)) {
$out.=',<br />';
}
$iter++;
}
echo $out;
You need an inner foreach loop to handle printing the array in $value as this is a multi dimensional array. The preceding is an example of how it could look to produce the exact output you requested. If you are looking for a dump of the values, then please use the var_dump solution provided by #meda.

There are two issues in your code. The first is that $value is an array, the second is that this array only contains one item.
Try this:
$data_array = array();
while($rs = mysql_fetch_assoc($result))
{
$key=$rs['id'];
$value=$rs['Sprinkler_ID'];
$data_array[$key][] = $value;
}
foreach ($data_array as $key => $values)
{
echo $key.'=> [';
foreach($values as $value)
echo $value . ',';
echo ']<br />';
}

Related

PHP Get duplicate values in array and average second value

I have an array that looks like this:
$ratingsInPosts = array
(
array("1",3),
array("2",5),
array("2",2),
array("5",2),
array("90",1),
array("5",6),
array("2",2),
);
I Want to find duplicate values in the first column and avarage its values from the second column.
So that this("1",3),("2",5),("2",2),("5",2),("90",1),("5",6),("2",2)
ends up like this ("1",3),("2",3),("5",4),("90",1)
Try this tested solution
I got the required Output
$ratingsInPosts = array
(
array("1",3),
array("2",5),
array("2",2),
array("5",2),
array("90",1),
array("5",6),
array("2",2),
);
$arr1 = array_column($ratingsInPosts, 0);
$p = array_count_values($arr1);
foreach($p as $key => $value)
{
$sum = 0;
for($i=0; $i < $value; $i++)
{
$pos = array_search($key, $arr1);
$sum += $ratingsInPosts[$pos][1];
unset($arr1[$pos]);
unset($ratingsInPosts[$pos]);
}
$re[] = array('"'.$key.'"',$sum/$value);
}
print_r($re);
I hope it helps you:
$groups = array();
// in this loop we group values by first column
foreach ($ratingsInPosts as $row) {
$key = $row[0];
if (!isset($groups[$key]) {
$groups[$key] = array();
}
$groups[$key][] = $row[1];
}
$result = array();
foreach ($groups as $key => $value) {
$avg = array_sum($value) / count($value);
$row = array($key, $avg);
$result[] = $row;
}
<?php
header('Content-Type: text/plain');
$ratingsInPosts = array(array("1",3),array("2",5),array("2",2),array("5",2),array("90",1),array("5",6),array("2",2));
$result = array();
$output = array();
foreach($ratingsInPosts as $array){
$result[$array[0]][] = $array[1];
}
foreach($result as $key=>$array){
$output[] = array($key,round(array_sum($array)/count($array)));
}
var_export($output);
?>

Loop into an array with PHP

I have the following array:
$array = [
['2017-02-26', '2017-02-27'],
['2017-03-01'],
['2017-01-01', '2017-01-02', '2017-01-03', '2017-01-04'],
['2017-01-05', '2017-01-06', '2017-01-07']
];
I'm looking to loop into this array to have something like this:
// When several dates
From 2017-02-26 to 2017-02-27.
// When only one date
On the 2017-03-01.
What I tried:
foreach ($array as $key => $value) {
$count = count($array[$key]);
if($count==1) {
echo "On the $key[$value]";
}
else {
$first = reset($array);
$last = end($array);
echo "From ".$first." to ".$last.;
}
}
But it doesn't work when there is only one date in the row.
You are looping by foreach() so it will display last echo string .Store result to one variable Eg($display) will be more easy to display that
$display = "";
foreach ($array as $key => $value) {
$count = count($array[$key]);
if($count==1) {
$display .= "On the $value[0] <br>";
}
else {
$first = $value[0];
$last = $value[$count-1];
$display .= "From ".$first." to ".$last."<br>";
}
}
echo $display;
Try this:-
foreach ($array as $key => $value) {
$count = count($value);
if($count==1) {
echo "On the ".$value[0];
}
else {
$first = reset($value);
$last = end($value);
echo "From ".$first." to ".$last;
}
}
Or just copy paste this code, it will work. Your main inside array to play with is $value.

PHP counting MYSQL rows that contain the same value in many columns

Here is the content of my table:
How to count all names in different table cells to get a result like this?
Bob-7
Alex-3
Ivan-5
Nina-5
.........
With this code:
<?php
$q= mysqli_query($db, 'SELECT * FROM names');
while ($all = mysqli_fetch_array($q)) {
$k1= $all['Name1'];
$k2= $all['Name2'];
$k3= $all['Name3'];
$k4= $all['Name4'];
$k5= $all['Name5'];
$k6= $all['Name6'];
$arr[]= $k1;
$total_values = array_count_values($arr);
}
foreach ($total_values as $key => $value) {
echo $key .'-'. $value .'<br>';
}
My output result is:
Bob-3
Alex-1
Ivan-1
Nina-2
When I change my code to:
<?php
$q= mysqli_query($db, 'SELECT * FROM names');
while ($all = mysqli_fetch_array($q)) {
$k1= $all['Name1'];
$k2= $all['Name2'];
$k3= $all['Name3'];
$k4= $all['Name4'];
$k5= $all['Name5'];
$k6= $all['Name6'];
$arr=array($k1, $k2);
$total_values = array_count_values($arr);
foreach ($total_values as $key => $value) {
echo $key .'-'. $value .'<br>';
}
}
My output result is:
Bob-1
Alex-1
Ivan-1
Nina-1
Nina-1
Bob-1
Bob-1
Ivan-1
Nina-1
Nina-1
.......
What is wrong and what I have to do to add $k2, $k3....$k6 in the array $arr?
This will count the number of occurences for a single name:
$q= mysqli_query($db, 'SELECT * FROM names');
$arr = array();
// 1) loop through rows
while ($all = mysqli_fetch_array($q, MYSQLI_NUM)) {
// 2) loop through cells in a row
foreach($all as $val) {
// 3) 'roll out' the values into a one-dimensional array
if(empty($val)) { continue; } // if you don't want to count empty cells
$arr[] = $val;
}
}
// 4) count the number of occurences
$names_qty = array_count_values($arr);
// optional loop that shows the results
foreach($names_qty as $name=>$qty) {
echo $name.'-'.$qty.'<br />';
}
The benefit of this solution is that you call the counting function only once and not in every iteration.
You have to accumulate data in a loop and print it after all data is processed.
$total = array();
$result = mysqli_query($db, 'SELECT * FROM names', MYSQLI_USE_RESULT);
while (mysqli_fetch_assoc($result) as $row) {
foreach ($row as $col => $value)
total[$col]++;
}
}
print_r($total);
This code is tested and should do the trick.
<?php
$arr = array();
$q = mysqli_query($db, 'SELECT * FROM names');
while ($all = mysqli_fetch_assoc($q)) {
foreach($all as $val) {
if(empty($val)) {
continue;
}
// saves all names with the name as key
$arr[$val][] = $val;
}
}
// Output
foreach($arr as $k => $v) {
// count how many times the name was pushed into the array
echo $k.' - '. count($v);
}

Merging and looping multi dimensional array

I'm trying to loop some array using foreach. This is the code which demonstrates what I'm doing
$q = "SELECT * "
."FROM ".TBL_FRUITSDETAILS."";
$fruitsdetails = $database->query($q);
$var = array();
while($line = mysql_fetch_assoc($fruitsdetails)){
$var[] = $line;
}
$q = "SELECT * "
."FROM ".TBL_NUMDETAILS."";
$numdetails = $database->query($q);
$var2 = array();
while($line2 = mysql_fetch_assoc($numdetails)){
$var2[] = $line2;
// $n++;
}
$out = array();
foreach ($var as $key => $value){
// $out[] = array_merge_recursive($value, $var2[$key]);
foreach ($var2 as $key => $value) {
$out1[] = array_merge_recursive($var[$key], $var2[$key]);
}
}
print_r(json_encode($out1));
However, this outputs
appleone
bananatwo
appleone
bananatwo
and I want to display it like this instead
appleone
appletwo
bananaone
bananatwo
Try this,
$var = array (1,2);
$var2 = array (a,b);
$out = array();
foreach ($var as $key => $value){
foreach($var2 as $k=>$v){
$out[] = $value.$v;
}
}
print_r(json_encode($out));
I think your loop should be something like this. There's no need of using array_merge_recursive function
$var = array (1,2);
$var2 = array ('a','b');
$result = array();
foreach($var as $key => $val){
foreach($var2 as $k => $v){
$result[] = $val.$v;
}
}
There is no need to use array_merge_recursive just a nested loop will suffice:
$var = array (1,2);
$var2 = array ('a','b');
$out = array();
foreach($var as $arrayNumeric){
foreach($var2 as $arrayAlphaNumeric){
$out[] = $arrayNumeric.$arrayAlphaNumeric;
}
}

getting duplicated results from nested foreach loop

I'm trying to get the following output from mysql for Google Line Chart API:
[["product","diameter","width"],["Product 1","2","4"],["Product 2","4","8"]]
I have set up several input checkboxes to send field names (e.g width,diameter) to the database via $_POST["info"] and retrieve the values from those fields. Here's the part that generates the data from mysql:
$result = $users->fetchAll();
$comma = "";
$data="";
$data[0] = array_merge(array(product),$info);
$i = 1;
foreach ($result as $r)
{
foreach($_POST["info"] as $p)
{
$d .= $comma.$r[$p]; // trying to get "$r["width"],$r["diameter"]"
}
$comma = ",";
$data[$i] = array($r["name"], $d);
$i++;
}
echo json_encode($data);
My desired output should be like this:
[["product","diameter","width"],["Product 1","2","4"],["Product 2","4","8"]]
But that code is generating duplicated results like this
[["product","diameter","width"],["Product 1","24"],["Product 2","24,4,8"]]
I guess I shouldn't be using the nested foreach to loop over $_POST. Can anyone tell me how to fix that?
Full PHP Code:
$info = $_POST["info"]; // It contains an array with values like width,diameter,thickness etc...
$comma = "";
foreach($info as $in)
{
$field .= "".$comma."b.".$in."";
$comma = ",";
}
$sql = "
SELECT {$field},a.user_id,a.name
FROM `product_detail` a INNER JOIN
`attr` b ON a.model = b.model
WHERE a.user_id = ?
GROUP BY a.model
";
$users = $dbh->prepare($sql);
$users->bindValue(1, $_SESSION["user_id"]);
$users->execute();
$result = $users->fetchAll();
$comma = "";
$data="";
$i = 1;
$data[0] = array_merge(array(product),$info);
foreach ($result as $r)
{
foreach($_POST["info"] as $p)
{
$d .= $comma.$r[$p];
}
$comma = ",";
$data[$i] = array($r["name"], $d);
$i++;
}
echo json_encode($data);
$_POST["info"] Content:
Array
(
[0] => diameter
[1] => width
)
try it like this:
$result = $users->fetchAll();
$data="";
$data[0] = array_merge(array(product),$info);
$i = 1;
foreach ($result as $r)
{
$d[]=$r["name"];
foreach($_POST["info"] as $p)
{
$d[]= $r[$p];
}
$data[$i] = $d;
$d=array(); //set $d to empty not to get duplicate results
$i++;
}
echo json_encode($data);
The end result you are looking for, is valid JSON. You should not try to manually generate that.
Instead you should make an array of arrays in php and use json_encode($array) to get the result you are looking for.
Also note that by injecting your POST variables directly in your query, you are vulnerable to sql injection. When accepting fields, you should check them against a white-list of allowed values.
Try the below solution:
$result = $users->fetchAll();
$data="";
$data[0] = array_merge(array(product),$info);
$i = 1;
foreach ($result as $r)
{
$d = array();
foreach($_POST["info"] as $p)
{
$d[] = $r[$p]; // trying to get "$r["width"],$r["diameter"]"
}
$data[$i] = array($r["name"]) +$d;
$i++;
}
echo json_encode($data);

Categories