so I have loop where it spits out each row of data from my database. Output show below
Array ( [0] => 1 [1] => 1 [2] => 1 [3] => Saratoga [4] => test [5] => 7-2 [6]
=> Red [7] => Bob [8] => Jill )
Array ( [0] => 2 [1] => 1 [2] => 2 [3] => Saratoga [4] => test 2 [5] => 3-3 [6]
=> White [7] => Bill [8] => Austin )
Array ( [0] => 3 [1] => 1 [2] => 3 [3] => Saratoga [4] => test 3 [5] => 2-2
[6] => Blue [7] => Austin [8] => jill )
how do I combine this into one array?
code is down below on how I am doing my loop for my array
$sql = "SELECT * FROM `2018-08-20`";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$rn = 1;
// output data of each row
$aa = 1;
while($row = $result->fetch_assoc()) {
$a = array($aa,$row["RaceNumber"], $row["HorseNum"], $row["Track"],
$row["HorseName"], $row["Odds"], $row["Color"], $row["JockeyName"],
$row["TrainerName"] );
for($x=0;$x < $a[1];$x++){
$aa++;
print_r($a);
echo "<br/>";
$rn++;
}
}
echo ' <button type="submit" name="submit"> Submit </button></form>';
echo "</table>";
} else {
echo "0 results";
}
Try this. In the following code we are storing all arrays in $all_data array.
$all_data = array();
while($row = $result->fetch_assoc()) {
$a = array($row["RaceNumber"], $row["HorseNum"], $row["Track"],
$row["HorseName"], $row["Odds"], $row["Color"], $row["JockeyName"],
$row["TrainerName"] );
$all_data[] = $a;
}
print_r($all_data);
If you just want an array containing the fields that you have coded in your loop, you should just code them into your query. I'm not sure what you are doing with the $aa in your array, but you have it there so I'm including it in my last example.
SQL APPROACH:
Note: The $aa will be missing.
$sql = "SELECT
`RaceNumber`,
`HorseNum`,
`Track`,
`HorseName`,
`Odds`,
`Color`,
`JockeyName`,
`TrainerName`
FROM `2018-08-20`";
$results = $conn->query($sql);
print_r($results);
YOUR CURRENT SETUP
$sql = "SELECT * FROM `2018-08-20`";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$rn = 1; //What are these for???
$aa = 1;
while($row = $result->fetch_assoc()) {
$a[] = array(
$aa,
$row["RaceNumber"],
$row["HorseNum"],
$row["Track"],
$row["HorseName"],
$row["Odds"],
$row["Color"],
$row["JockeyName"],
$row["TrainerName"]
);
}
print_r($a);
echo ' <button type="submit" name="submit"> Submit </button></form>';
echo "</table>";
} else {
echo "0 results";
}
You can try this also
$all_data = array();
while($row = $result->fetch_assoc()) {
$all_data[] = $row;
}
var_dump($all_data);
As the $row will be in array format , you can directly add that to array
you can read more on
http://php.net/manual/en/mysqli-result.fetch-assoc.php
Related
I am confused with array.
What I want to do is two merge two array, but this kind of the two array are different:
Array
(
[0] => Array
(
[sud] => 60
[sad] => Array
(
[incharge] => Perusahaan
[perusahaan_id] => 1
[barang_id] => 3
[gudang_id] => 2
[stock] => 1
)
)
[1] => Array
(
[sud] => 23
[sad] => Array
(
[incharge] => Perusahaan
[perusahaan_id] => 1
[barang_id] => 4
[gudang_id] => 1
[stock] => 2
)
)
)
I want to move the array of [sud] into [sad] array, and named it as quantity.
This is my codes which generate the array above:
if($q->num_rows() > 0)
{
foreach ($q->result() as $row => $rows)
{
$data[] = $rows;
$stock[] = $rows->stock;
}
}
$i = -1;
foreach ($update as $updates)
{
$i++;
$test3['sud'] = $stock[$i];
$test3['sad'] = $updates;
$happy[] = $test3;
}
print_r ($happy);
What I want to do here actually is to check if the number of array [stock] => value is not bigger than the number in array [sud].
Please help, thanks in advance.
If I understood well, you want to change it like this:
if($q->num_rows() > 0)
{
foreach ($q->result() as $row => $rows)
{
$data[] = $rows;
$stock[] = $rows->stock;
}
}
$i = -1;
foreach ($update as $updates)
{
$i++;
$test3['sad'] = $updates;
$test3['sad']['quantity'] = $stock[$i];
$happy[] = $test3;
}
print_r ($happy);
I have following array:
Array
(
[0] => ALFA01
[1] => BETA02
[2] => GAMMA03
[3] => DELTA04
[4] => EPSILON05
[5] => ZETA06
[6] => THETA07
[7] => IOTA08
[8] => KAPPA09
[9] => LAMBDA10
)
Then I separate the values into characters and numbers in the following way:
foreach($portfolio as $value) {
$char = substr("$value", 0, 2);
$numb = substr("$value", 2);
and do a query using this values:
$query = "
SELECT id, typ1, typ2, typ3
FROM data_table
WHERE char = '$char'
AND numb = $numb
LIMIT 1";
$result = mysqli_query($mysqli, $query);
//Now we have some important variables that will help finding our result.
while($row = mysqli_fetch_array($result)) {
$id = $row['id'];
$typ1 = $row['typ1'];
$typ2 = $row['typ2'];
$typ3 = $row['typ3'];
}
Then I do some queries in case typ* are = 1 (it can be only 0 or 1).
if ($typ1 == 1) {
$query_id_num2 = "
SELECT id_num2
FROM values_table01
WHERE id_num1 = $id";
$result_id_num2 = mysqli_query($mysqli, $query_id_num2);
// Return an array with all ids.
$id_num2_typ01 = array();
while($row = mysqli_fetch_array($result_appln_id_num2)) {
$id_num2_typ01[] = ($row['id_num2']);
}
}
/== EDIT ==/
In each different typ we have a different values_table.
I'm now writing the complete query for typ2, so it will be emphasised.
// == /EDIT ==/
Then I do the same to typ2 and typ3...
if ($typ2 == 1) {
$query_id_num2 = "
SELECT id_num2
FROM values_table02
WHERE id_num1 = $id";
$result_id_num2 = mysqli_query($mysqli, $query_id_num2);
// Return an array with all ids.
$id_num2_typ02 = array();
while($row = mysqli_fetch_array($result_appln_id_num2)) {
$id_num2_typ02[] = ($row['id_num2']);
}
}
etc.
In the end I merge the three arrays (if they are set) and print the result on the screen:
// typ01
if (isset($id_num2_typ01)){
$id_num2_typ01 = $id_num2_typ01;
} else {
$id_num2_typ01 = array();
}
// typ02
if (isset($id_num2_typ02)){
$id_num2_typ02 = $id_num2_typ02;
} else {
$id_num2_typ02 = array();
}
// typ03
if (isset($id_num2_typ03)){
$id_num2_typ03 = $id_num2_typ03;
} else {
$id_num2_typ03 = array();
}
// merge arrays
$id_num2 = array_merge($id_num2_typ01,$id_num2_typ02,$id_num2_typ03);
// print it on screen
echo '<pre>id_num2:<br />';
print_r($appln_idNum2);
echo '</pre>';
} // this closes the above foreach, i.e. the code will loop to every value of the first array
As result I receive for example following data:
id_num2:
Array
(
[0] => 41558194
[1] => 44677841
[2] => 44503689
[3] => 40651770
[4] => 41667291
)
id_num2:
Array
(
[0] => 15458354
[1] => 35477154
[2] => 15703123
[3] => 95151111
[4] => 55567125
)
etc.
In our case we will have 10 small arrays like that.
My problem is: How can I merge this small arrays so in the ende I have only one array?
Thank you for your help to solve this particular problem. Maybe is there also another possibility to write the code to be better and more efficient.
My head is exploding with this. I can't seem to create a working solution.
I have a file in this format:
99895|35378|0.01
99895|813|-0.97
99895|771|0.29
442|833|-1.06
442|485|-0.61
442|367|-0.14
442|478|0.77
442|947|-0.07
7977|987|0.76
7977|819|0.37
7977|819|0.36
7977|653|1.16
7977|1653|1.15
I want to calculate average values from third column for each id from the first column.
This seems so easy but I can't get this to work. How do you get averages for any said id from first column?
EDIT:
Some sample code I've written before:
$file = file_get_contents("results.txt");
$file = explode("
", $file);
$howMany = count($file);
for($a = 0;$a<$howMany;$a++)
{
$row = explode("|", $file[$a]);
$id = $row[0];
$howManyAlready = count($bigTable[$id]);
$bigTable[$id][$howManyAlready] = $row[2];
}
I've added the code. So far it gets the results into an array ( with offset corresponding to its id ) But I am having trouble with how to get those results and calculate average for each id and then present it on the screen.
Something like this should definitely work..
<?php
$arr=array();
$arrv=array_filter(file('myfile.txt'),'strlen');
foreach($arrv as $v)
{
array_push($arr,#array_pop(explode('|',$v)));
}
echo $avg = array_sum($arr)/count($arr);
You can try doing this :
$file = file_get_contents("results.txt");
$file = explode("
", $file);
$valuesPerID = Array();
foreach($file as $row)
{
$row_array = explode("|", $row);
$id = $row_array[0];
if(!array_key_exists($id, $valuesPerID))
{
$valuesPerID[$id] = Array();
}
$valuesPerID[$id][] = $row_array[2];
}
Now in the $valuesPerID array, you'll have all your ID as keys, and for each ID, all the values associated with the said ID. They you can easily calculate the average of these values !
You can use array mapping to assign value and id.
For example (assume that you have handled the text):
<?php
$data = array("99895|35378|0.01",
"99895|813|-0.97",
"99895|771|0.29",
"442|833|-1.06",
"442|485|-0.61",
"442|367|-0.14",
"442|478|0.77",
"442|947|-0.07",
"7977|987|0.76",
"7977|819|0.37",
"7977|819|0.36",
"7977|653|1.16",
"7977|1653|1.15");
$bucket = array();
$count = array();
foreach($data as $line) {
list($id, $what_s_this, $number) = explode("|", $line);
$count[$id]++;
$bucket[$id]+= (float)$number;
}
foreach($bucket as $id => $sum) {
echo "id:". $id. ", average". $sum / $count[$id]. "\n";
}
This should put you on the right track.
<?php
$values = array();
foreach (file('file.txt') as $line) {
list($id, $thingymabob, $value) = explode('|', $line);
if ( ! array_key_exists($id, $values)) {
$values[ $id ] = array();
}
array_push($values[ $id ], $value);
}
foreach ($values as $id => $value) {
printf(
"%d has an average of %f\n",
$id,
array_sum($value) / count($value)
);
}
Here some something I've just written.
In my example it takes it from a string.
<?php
$test1 = "";
$test2 = "";
$count1 = 0;
$count2 = 0;
$string = "99895|35378|0.01
99895|813|-0.97
99895|771|0.29
442|833|-1.06
442|485|-0.61
442|367|-0.14
442|478|0.77
442|947|-0.07
7977|987|0.76
7977|819|0.37
7977|819|0.36
7977|653|1.16
7977|1653|1.15";
$d = explode("\n", $string);
foreach ($d as $k => $v)
{
$d2 = explode("|", $v);
if ($d2[0] == '99895'){
$count1++;
$test1 += $d2[2];
}
if ($d2[0] == '442'){
$count2++;
$test2 += $d2[2];
}
}
$result1 = $test1 / $count1;
$result2 = $test2 / $count2;
echo $result1. " <br> ". $result2;
I don't know how well this will work as I don't know if the values are set or not.
If You try below code
<?php
$file_content = array();
$handle = fopen("test.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
// process the line read.
$line_ex = explode("|",$line);
array_push($file_content,$line_ex);
}
} else {
// error opening the file.
}
echo "<pre>";
print_r($file_content);
echo "<pre>";
?>
then You will get below output
Array
(
[0] => Array
(
[0] => 99895
[1] => 35378
[2] => 0.01
)
[1] => Array
(
[0] => 99895
[1] => 813
[2] => -0.97
)
[2] => Array
(
[0] => 99895
[1] => 771
[2] => 0.29
)
[3] => Array
(
[0] => 442
[1] => 833
[2] => -1.06
)
[4] => Array
(
[0] => 442
[1] => 485
[2] => -0.61
)
[5] => Array
(
[0] => 442
[1] => 367
[2] => -0.14
)
[6] => Array
(
[0] => 442
[1] => 478
[2] => 0.77
)
[7] => Array
(
[0] => 442
[1] => 947
[2] => -0.07
)
[8] => Array
(
[0] => 7977
[1] => 987
[2] => 0.76
)
[9] => Array
(
[0] => 7977
[1] => 819
[2] => 0.37
)
[10] => Array
(
[0] => 7977
[1] => 819
[2] => 0.36
)
[11] => Array
(
[0] => 7977
[1] => 653
[2] => 1.16
)
[12] => Array
(
[0] => 7977
[1] => 1653
[2] => 1.15
)
)
For determining average value from third column of corresponding first column - I am researching on it. When I will be done I'll put it here.
Try this:
$filename = 'results.txt';
$result = $counter = $values = array();
$file = fopen($filename, 'r') or die("Couldn't open $filename");
while ($line = fgets($file)) {
$content = explode('|', $line);
if (empty($content[0]) or empty($content[2]))
continue;
$values[$content[0]][] = (float) $content[2];
++$counter[$content[0]];
}
foreach ($values as $key => $value) {
$result[$key] = array_sum($value) / $counter[$key];
}
fclose($file);
How can I create an array like the following in PHP from a database result set using a loop:
Array
(
[T] => Array
(
[0] => Array
(
[id] => 1
[name] => Timer
)
[1] => Array
(
[id] => 2
[name] => Tub
)
)
[P] => Array
(
[0] => Array
(
[id] => 3
[name] => Paper
)
[1] => Array
(
[id] => 4
[name] => Puppy
)
)
)
You will notice that the array keys are a letter, which is taken from the 'name' value in the result set. The loop will be something like this:
while($result = $db->fetch($query) {
$key = $result['name']{0};
// your answer :-)
}
I think something like this should do it:
$sql = 'SELECT id, name FROM table';
$result = mysql_query( $sql);
$answer = array();
while( $row = mysql_fetch_assoc( $result))
{
$answer[ strtoupper($row['name'][0]) ][] = $row;
}
mysql_free_result( $result);
var_dump( $answer);
OR, to be more specific (if your query is returning more columns than just id and name):
while( $row = mysql_fetch_assoc( $result))
{
$answer[ strtoupper($row['name'][0]) ][] = array(
'id' => $row['id'],
'name' => $row['name']
);
}
$indexArray = array(); // Array from Example
while($result = $db->fetch($query) {
$key = $result['name']{0};
if(!isset($indexArray[$key])) {
$indexArray[$key] = array();
}
array_push($indexArray[$key], $result);
}
$results = array();
while($result = $db->fetch($query)) {
$key = strtoupper($result['name'][0]);
if(!isset($results[$key]))
$results[$key] = array();
$results[$key][] = $result;
}
I have a PHP code like that:
$cityCount=10;
$currentUsers = array();
$addedUsers = array();
for ($cityId = 1; $cityId <= $cityCount; $cityId++) {
$currentUsers[$cityId] = array();
$addedUsers[$cityId] = array();
}
However, I want to change the for and I want to define an array for cities because new city will be added and it'i city id will be 22(not 11. If it could be 11 there was going to be just one change at code $cityCount=11; but city id is not sequential now.)
As like:
[1,2,3,4,5,6,7,8,9,10,22]
I want to iterate over that array.
Also I have a code like that:
for ($cityId = 1; $cityId <= $cityCount; $cityId++) {
foreach ($addedUsers[$cityId] as $userId) {
if($added) $addSql .= ",\n";
$addSql .= '(' . $userId . ", " . $cityId . ')';
$added++;
}
How to change this code according to new version of code?
$citiesids = array(1,2,3,4,5,6,7,8,9,10,22);
$currentUsers = array();
$addedUsers = array();
foreach ($citesids as $cityId) {
$currentUsers[$cityId] = array();
$addedUsers[$cityId] = array();
}
is that what you need?
Use foreach:
$cities = array(1,2,3,4,5,6,7,8,9,10,22);
foreach ($cities as $cityId) {
// use $cityId as before.
}
I'm not really sure what you mean exactly, but perhaps you mean using the array of cityIds instead of a simple counter?
In that case, simply use a foreach:
foreach ($cities as $cityId)
I assume you want to iterate over cities, but not all of them
$cityCount=22;
$cities = array(1,2,3,4,5,6,7,8,9,10,22);
for ($cityId = 1; $cityId <= $cityCount; $cityId++) {
// only handle the cases that where cityid is in the cities-array
if (!in_array($cityId, $cities)) continue;
// do what you like here
}
$cityCount=10;
$currentUsers = array();
$addedUsers = array();
for ($cityId = 1; $cityId <= $cityCount; $cityId++) {
$currentUsers[$cityId] = array();
array_push($addedUsers,$cityId);
}
echo '<pre>';
print_r($addedUsers);
echo '</pre>';
array_push($addedUsers,22);//whatever city you want to added (22 for example)
echo '<pre>';
print_r($addedUsers);
echo '</pre>';
OUTPUT
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
[7] => 8
[8] => 9
[9] => 10
)
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
[7] => 8
[8] => 9
[9] => 10
[10] => 22 // just Added
)
As I suspected, it should be SQL query, not PHP code
Something like
select * from user WHERE where city IN (SELECT * FROM cities)
or whatever suits your hidden and secret needs