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);
}
Related
I am having a problem in JSON. I want to sort my JSON in increasing order of variable id.
This is JSON data at present
{"server_response":[{"id":"9","email":"test#gmail.com=","password":"test"},{"id":"5","email":"json#gmail.com","password":"json"},{"id":"14","email":"wrong#gmail.com","password":"test"},{"id":"13","email":"mail#gmail.com=","password":"mail"}]}
php file i am using right now is
<?php
require_once('dbConnect.php');
$sql = "select * from users;";
$result = mysqli_query($con,$sql);
$response = array();
while($row = mysqli_fetch_array($result))
{
array_push($response,array("id"=>$row[0],"email"=>$row[1],"password"=>$row[2]));
}
echo json_encode(array("server_response"=>$response));
mysqli_close($con);
?>
But i want my output as shown below.Any changes for php file ???
{"server_response":[{"id":"5","email":"json#gmail.com","password":"json"},{"id":"9","email":"test#gmail.com=","password":"test"},{"id":"13","email":"mail#gmail.com=","password":"mail"},{"id":"14","email":"wrong#gmail.com","password":"test"}]}
You can sort in your client side but it would be better if you do it from the server side only. What you need to do is:
$sql = "select * from users order by id;";
This should work. If you want it in descending order, add the keyword: 'desc' after id (without the single quotes).
Try below Code...
<?php
$json = '{"server_response":[{"id":"9","email":"test#gmail.com=","password":"test"},{"id":"5","email":"json#gmail.com","password":"json"},{"id":"14","email":"wrong#gmail.com","password":"test"},{"id":"13","email":"mail#gmail.com=","password":"mail"}]}
';
$arr = json_decode($json,true); //Converts your json into array
$main = $arr['server_response']; // your array for sorting
$list = array_sort($main, 'id', SORT_ASC); //makes function call
print_r($list); //desired result
function array_sort($array, $on, $order=SORT_ASC){
$new_array = array();
$sortable_array = array();
if (count($array) > 0) {
foreach ($array as $k => $v) {
if (is_array($v)) {
foreach ($v as $k2 => $v2) {
if ($k2 == $on) {
$sortable_array[$k] = $v2;
}
}
} else {
$sortable_array[$k] = $v;
}
}
switch ($order) {
case SORT_ASC:
asort($sortable_array);
break;
case SORT_DESC:
arsort($sortable_array);
break;
}
foreach ($sortable_array as $k => $v) {
$new_array[$k] = $array[$k];
}
}
return $new_array;
}
?>
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.
This is my code:
session_start();
/* loops through each row in the global $_SESSION variable which
contains the array and uses the $value to GET the data in the text
boxes and output them */
// studevent_result =
foreach ($_SESSION['arrayNameResult'] as $value) {
$studResult = $_GET[$value];
echo $studResult;
echo "<br>";
}
// result_postion =
foreach ($_SESSION['arrayNamePosition'] as $value) {
$studPosition = $_GET[$value];
echo $studPosition;
echo "<br>";
}
echo "<br>";
// stud_id =
foreach ($_SESSION['arrayId'] as $value) {
echo $value;
echo "<br>";
}
// UPDATE query, this will update the studevent_result and result_position
// column in the database for the specific stud_id.
$updateQuery = "
UPDATE result
SET studevent_result = '00:20:33',
result_position = '6'
WHERE result.stud_id = '12'
";
$updateRow = mysqli_query($conn, $updateQuery);
I use $_SESSION variables which all store an array. I extract the results of these arrays using foreach loops.
In $updateQuery, I want to make studevent_result = to the results of my first foreach loop above, result_position = to the results of the second foreach loop above and the result.stud_id = to the results of the third foreach loop above.
After me editing the code my code now looks like this:
foreach ($_SESSION['arrayNameResult'] as $value) {
$studResult = $_GET[$value];
foreach ($_SESSION['arrayNamePosition'] as $data) {
$studPosition = $_GET[$data];
foreach ($_SESSION['arrayId'] as $idValue) {
echo $idValue;
$updateQuery = "
UPDATE result
SET studevent_result = '$studResult',
result_position = '$studPosition'
WHERE result.stud_id = '$idValue'
";
$updateRow = mysqli_query($conn, $updateQuery);
}
}
}
I nested the foreach loops. But the problem now is that for the last foreach loop in the nested loops, $idValue in the query only uses the last element in the array $_SESSION['arrayId']. How can I fix this to loop throught the whole array, so that the query uses all the values in the array?
Thanks in advance.
If I understood your issue this should help you
session_start();
$i = 0;
$studResult = array();
foreach ($_SESSION['arrayNameResult'] as $value) {
$studResult[$i] = $_GET[$value];
$i++;
}
$studPosition= array();
$i=0;
foreach ($_SESSION['arrayNamePosition'] as $value) {
$studPosition[$i] = $_GET[$value];
$i++;
}
$stud_id = array(); $i=0;
foreach ($_SESSION['arrayId'] as $value) {
$stud_id[$i] = $value; $i++;
}
for($j =0; $j<$i; $j++){
$updateQuery = "
UPDATE result
SET studevent_result = '$studResult[$j]',
result_position = '$studPosition[$j]'
WHERE result.stud_id = '$stud_id[$j]'
";
$updateRow = mysqli_query($conn, $updateQuery);
}
Hope it will be helpful. Happy coding :)
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 />';
}
If i echo inside the while loop i get 4,2 values and if i echo outside the while loop then i only get 2. I want to get the data from $row into the values array. is something missing in this code?
$query = oci_parse($con, "SELECT count(*) FROM Counter GROUP BY Blog_name");
oci_execute($query);
while($row = oci_fetch_array($query))
{
$s = $row[0].',';
$values = explode(',', $s);
echo $values[0]; // 4
echo $values[1]; // 2
}
echo $values[0]; // 2
echo $values[1]; // 2
Try this,
$Values = array();
while($row = oci_fetch_array($query))
{
$Values[] = $row[0];
}
echo $Values[0];
First, $values as you're using it is just a string, and is not an array.
Try adding before the while loop.
$values = array();
Second, there's really no need to use explode here, it's an unnecessary step. If you only want the first column in the row, you can simply add that column to $values. (Currently you are overwriting the contents of $values at each iteration of the loop because you are missing the [].)
$values[] = $row[0];
If you're trying to put ALL of the columns in each row into values, try:
$values[] = $row;
If you're trying to individually put the contents of each column into it's own index in $values, try:
while($row = oci_fetch_array($query))
{
foreach($row as $column)
{
$values[] = $column;
}
}
Do like this:
$s = array();
while($row = oci_fetch_array($query)) {
$s[] = $row[0];
}
echo $s[0];
print_r($s);
$query = oci_parse($con, "SELECT count(*) FROM Counter GROUP BY Blog_name");
oci_execute($query);
$values = array();
while($row = oci_fetch_array($query))
{
$values[] = $row[0];
}
print_r($values);