This question has already been asked tons of times, but I can't really understand how to do this.
I'm trying to insert the values of an entire row, into an array in PHP.
Here is the query result:
+-----+-----+------+------+------+------+------+-----+
+ Ln1 + Ln2 + Mar1 + Mar2 + Mar3 + Mer1 + Mer2 + Mer3+
+-----+-----+------+------+------+------+------+-----+
+ 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 +
+-----+-----+------+------+------+------+------+-----+
I would like to insert all those '1' into an array called $giorni, actually I'm using
$arr_prep= array("Ln1","Ln2","Mar1","Mar2","Mar3","Mer1","Mer2","Mer3");
$giorni = array();
for($c = 0; $c < 8; $c++){
$temp = mysql_fetch_array(mysql_query("SELECT '$arr_prep[$c]' FROM Corsi WHERE id='$id'"));
array_push($giorni,$temp);
}
And the result printed with "echo "giorni -->".array_values($giorni);" is:
giorni -->Arraygiorni -->Arraygiorni -->Arraygiorni -->Arraygiorni -->Arraygiorni -->Arraygiorni -->Arraygiorni -->Array
I've also tried with mysql_fetch_array and mysql_fetch_row, maybe I'm using them in the wrong way but I could not make it work.
Can anyone suggest me how to do it?
Thanks
Try Changing SELECT '$arr_prep[$c]' FROM... to SELECT $arr_prep[$c] FROM..
Remove ''
you'll get output as
Array ( [0] => 1 1 => 1 [2] => 1 [3] => 1 [4] => 1 [5] => 1 [6] => 1 [7] => 1 )
Related
i have a assingment and i am so confuse i dont know how to solve my problem,
Assingment :
Make a system which should have the capability to analyze the total number of possible notes in a given amount using only if statement,
Example
Input:
Input amount: 575
Output
Total number of notes:
500: 1
100: 0
50: 1
20: 1
10: 0
5: 1
2: 0
1: 0
plese tell me how i write code of this,
i need your help i don't know how i make this,
Assuming the keys won't change:
<?php
function getPossibleNotes($input, $keysArray = [500, 100, 50, 20, 10, 5, 2, 1])
{
$responseArray = array_combine($keysArray, array_fill(0, count($keysArray), 0));
foreach($keysArray as $comparison){
if($input >= $comparison){
$input -= $comparison;
$responseArray[$comparison] = 1;
}
if($input <= 0){
break;
}
}
return $responseArray;
}
//When Input = 575
print_r(getPossibleNotes(575));
/*
Array
(
[500] => 1
[100] => 0
[50] => 1
[20] => 1
[10] => 0
[5] => 1
[2] => 0
[1] => 0
)
*/
Edit: if you need the count of the notes (As I see in other answers), do this replacement:
$responseArray[$comparison]++;
I have a query that returns a list of rows from mysql database, the list of rows generated have of rows values being the same.
Table
id mAmount paidAmount
1 100 50
1 100 30
2 200 20
2 200 150
I actually want to sum the paidAmount and subtract from just one of mAmount value per the same id.
For instance
1 | (100) - (50 + 0) = 50 |
1 | (100) - (30 + 50) = 20 |
2 | (200) - (20 + 0) = 180 |
2 | (200) - (150 + 20) = 30 |
I do not want anyone any to give me the entire codes to this, but an idea as to how to go about it using either php with while loop or possibly foreach statements. Thanks really appreciate.
Just have to loop and accumulate the paid amount, then do the subtraction.
For this example I suppose you pre-order your records by id and pass the records to an multidimensional array called rows:
$currentId = $rows[0]['id'];
$accumulated = 0;
foreach ( $rows as $row ) {
if ( $row['id'] != $currentId ) {
$accumulated = 0;
$currentId = $row['id'];
} // end if not current id
$accumulated += $row['paidAmount'];
$balance = $row['mAmount'] - $accumulated;
$row['balance'] = $balance;
$result[] = $row;
} // end foreach
print_r ( $result );
Results are printed like this:
Array
(
[0] => Array
(
[id] => 1
[mAmount] => 100
[paidAmount] => 50
[balance] => 50
)
[1] => Array
(
[id] => 1
[mAmount] => 100
[paidAmount] => 30
[balance] => 20
)
[2] => Array
(
[id] => 2
[mAmount] => 200
[paidAmount] => 20
[balance] => 180
)
[3] => Array
(
[id] => 2
[mAmount] => 200
[paidAmount] => 150
[balance] => 30
)
)
I am a bit 'rusty with php as it happens that sometimes I use it for weeks and sometimes it happens that you do not use for months. Either way I'm trying to pass values of another array are "array", on another array in an orderly manner ... What I want to do is essentially create a key that allows me to organize incremental values per line, in particular;
array content
Array
(
[key] => value
[2] => 1
[3] => Inter
[4] => 4
[5] => 4
[6] => 0
[7] => 0
[8] => 5
[9] => 1
[10] => +4
[11] => 12
[12] => Chievo Verona - Inter 0 - 1
[13] => Inter - Milan 1 - 0
[14] => Carpi - Inter 1 - 2
[15] => Inter - Atalanta 1 - 0
[16] => ;
[17] => 2
[18] => Torino
[19] => 4
[20] => 3
[21] => 1
[22] => 0
[23] => 9
[24] => 4
[25] => +5
[26] => 10
[27] => Torino - Sampdoria 2 - 0
[28] => Hellas Verona - Torino 2 - 2
[29] => Torino - Fiorentina 3 - 1
[30] => Frosinone - Torino 1 - 2
[31] => ;
[32] => 3
[33] => Fiorentina
[34] => 4
[35] => 3
[36] => 0
[37] => 1
[38] => 5
[39] => 3
[40] => +2
[41] => 9
[42] => Carpi - Fiorentina 0 - 1
[43] => Fiorentina - Genoa 1 - 0
[44] => Torino - Fiorentina 3 - 1
[45] => Fiorentina - Milan 2 - 0
[46] => ;
[47] => 4
[48] => Roma
[49] => 4
[50] => 2
the ";" It'll need to be able to recognize where you break the line, I do not remember if there is any method that allows me to access the next key.
Currently my code is:
$classifica = array("key" => "value");
function buildArrayClassifica()
{
global $array;
global $classifica;
$i = 0;
foreach(array_slice($array,1) as $key => $value)
{
if($value != ";")
{
array_push($classifica[$i], $value); //there is a problem
echo $value . " ";
}
else if($value == "value ")
{
continue;
}
else
{
$i++;
echo "<br/>";
}
}
}
The code I will return this error:
Warning: array_push () Expects parameter 1 to be array, null given in...
in particular on array_push, it seems not to accept incremental keys or maybe I'm doing it the wrong way.
Can anyone tell me how to solve?
UPDATING
As you have seen the issue is not simple and it is quite difficult to explain the problem, but I will try to be even clearer to meet.
As you can see above you are the structure of the array "array", but is a disordered structure that needs to be ordered in an additional array. To recapitulate the structure of the array "array" is:
1 , Inter , 4 , 4 , 0 , 0 , 5 , 1 , +4 , 12 , Chievo Verona - Inter 0 - 1 , Inter - Milan 1 - 0 , Carpi - Inter 1 - 2 , Inter - Atalanta 1 - 0 , ;
the ";" means that the line is finished. So the next value near the ";" means that a new line coming. What I need is move all the value of "array" in array classifica, but I want organize them for:
ROW1 => 1 , Inter , 4 , 4 , 0 , 0 , 5 , 1 , +4 , 12 , Chievo Verona - Inter 0 - 1 , Inter - Milan 1 - 0 , Carpi - Inter 1 - 2 , Inter - Atalanta 1 - 0
ROW2 => Other values...
So the ROW1, 2 .. rapresents the key of the array classifica. I'm trying to push the value inside a row and after it increment $i index but the code doesn't add the value because the index replace in loop the actual key, for example:
actual foreach content:
$i = 0
value = "Inter"
content of array=> [0] => Inter
now the $i is ever 0 because the row isn't finished yet, the ";"
it has not yet been reached, so the next content of foreach is:
"1" but replace the "Inter" value, so this is a problem.
You cannot use array_push() in this way. Please try:
$classifica = array();
function buildArrayClassifica()
{
global $array;
global $classifica;
$i = 0;
foreach(array_slice($array,1) as $key => $value)
{
if($value != ";")
{
$classifica[$i] = $value;
echo $value . " ";
}
else if($value == "value ")
{
continue;
}
else
{
$i++;
echo "<br/>";
}
}
}
This will create indexes (the value of $i) when $value is added to your array. array_push() would place the $value at the next numerical index and may not be what you want by the looks of it. You could also use $key if you wanted the index to match.
EDIT
After more discussion, you have a specific format, where the first Item is the Key, the following indexes are values, and when you encounter the value ";", it starts the sequence over. So when we read:
[2] => 1
[3] => Inter
[4] => 4
[5] => 4
[6] => 0
[7] => 0
[8] => 5
[9] => 1
[10] => +4
[11] => 12
[12] => Chievo Verona - Inter 0 - 1
[13] => Inter - Milan 1 - 0
[14] => Carpi - Inter 1 - 2
[15] => Inter - Atalanta 1 - 0
[16] => ;
The first value, '1' is our Index, the following values become the Value for this Index, and we stop reading when we find ";". That would look something like:
<?php
function buildArrayClassifica($dataArray){
$resultArray = array();
$t = array_values($dataArray);
print_r($t);
$lsc = 0;
foreach($t as $k => $v){
if((string)$v == ';'){
echo "<p>Found ';' at [$k] => {$v}</p>";
// Found end of data
// Save position
$scp = $k;
echo "<p>Recorded [$scp] position for ';'.</p>";
// Reset to find the Index, first int in this series
$c=$lsc; // First pass this should be 0
// Set the index
if($lsc ==0){
// First pass
$index = intval($t[$c]);
echo "<p>Getting Index from position [" . ($c) ."] => $index for Result Array.</p>";
$c++;
} else {
$c++;
$index = intval($t[$c]);
echo "<p>Getting Index from position [" . ($c) ."] => $index for Result Array.</p>";
$c++;
}
echo "<p>Starting to read data from [$c] until [$scp].</p>";
// Init implode variable
$data = "";
for($c;$c<$scp;$c++){
//Populate variable with the series up to semicolon, skipping first element (index)
$data .= $t[$c] . ", ";
}
echo "<p>Data collected for this round: '" . htmlentities(substr($data,0,-2)) . "'</p>";
// populate result array
$resultArray[$index] = substr($data,0,-2);
echo "<p>resultArray[$index] => " . htmlentities($resultArray[$index]) . "</p><br />";
$lsc = $scp;
}
}
return $resultArray;
}
$oldArray = array(1, "Inter", 4 , 4 , 0 , 0 , 5 , 1 , "+4" , 12 , "Chievo Verona - Inter 0 - 1", "Inter - Milan 1 - 0", "Carpi - Inter 1 - 2", "Inter - Atalanta 1 - 0", ";", 2, "Torino", 4, 3, 1, 0, 9, 4, '+5', 10, "Torino - Sampdoria 2 - 0", "Hellas Verona - Torino 2 - 2", "Torino - Fiorentina 3 - 1", "Frosinone - Torino 1 - 2", ";", 3, "apple", 0, 4, 6, "apple", ";");
$classifica = buildArrayClassifica($oldArray);
print_r($classifica);
?>
My initial testing seems to work for what you described. The first element of the array becomes the Index, the next few values become imploded until we reach the semicolon (;) value.
What I see as a result:
Array ( [1] => Inter, 4, 4, 0, 0, 5, 1, +4, 12, Chievo Verona - Inter 0 - 1, Inter - Milan 1 - 0, Carpi - Inter 1 - 2, Inter - Atalanta 1 - 0 [2] => Torino, 4, 3, 1, 0, 9, 4, +5, 10, Torino - Sampdoria 2 - 0, Hellas Verona - Torino 2 - 2, Torino - Fiorentina 3 - 1, Frosinone - Torino 1 - 2 [3] => apple, 0, 4, 6, apple )
ASIDE
If it were me, I would push it all into an array like so:
$data = array();
for($c;$c<$scp;$c++){
$data[] = $t[$c];
}
$resultArray[$index] = $data;
Or if you really want a string:
$resultArray[$index] = implode(", ", $data);
Hope that helps.
I am working on a survey application using MySql and PHP
The responses will be in the following format:
+-c1_1-+-c1_2-+-c1_3-+-c1_1-+-c1_2-+-c1_3-+-....
+ red + blue + pink + cyan + red + gray + ....
+ black+ pink + plum + red + blue + gray + ....
+ cyan + red + blue + blue + pink + plum + ....
+------+------+------+------+------+------+ ....
c1_1 represents Column_For_Question_1_With_Rank_1
c1_2 represents Column_For_Question_1_With_Rank_2
c1_3 represents Column_For_Question_1_With_Rank_3
c2_1 represents Column_For_Question_2_With_Rank_1
c2_2 represents Column_For_Question_2_With_Rank_2
c2_3 represents Column_For_Question_2_With_Rank_3
Scoring is like this:
Rank 1 = color in column cX_1 = gets 3 marks (c1_1,c2_1,c3_1..)
Rank 2 = color in column cX_2 = gets 2 marks (c1_2,c2_2,c3_2..)
Rank 3 = color in column cX_3 = gets 1 mark (c1_3,c2_3,c3_3..)
Score of Red:
appears in cX_1 two time = 3x2=6
appears in cX_2 two times = 2x2=4
So Red gets a score of 6+4=10
Score of Blue:
appears in cX_1 one time = 3x1=3
appears in cX_2 two times = 2x2=4
appears in cX_3 two times = 1x2=2
So blue gets a score of 3+4+2 = 9
Is it possible to write an effective query to arrive at a result like:
+-color-+-score-+
+ red + 10 +
+ blue + 9 +
+ xxx + # +
+ xxx + # +
+ xxx + # +
+-------+-------+
If that is not possible, atleast the number of occurances like:
+-color-+-n_cX_1-+-n_cX_2-+-n_cX_3-+
+ red + 2 + 2 + 0 +
+ blue + 1 + 2 + 2 +
+ xxx + # + # + # +
+ xxx + # + # + # +
+ xxx + # + # + # +
+ xxx + # + # + # +
+-------+--------+--------+--------+
Actually the colors will be replaced by people names.
Each 'set of three consecutive columns' (cX_1,cX_2,cX_3) represent first, second and third ranks rated for each of 9 questions. So there will be 3x9=27 columns
Can someone please help me with this? I am thinking on using count(*) repeatedly but I am sure it is a wrong approach. Searched a lot before posting but could not solve it.
Edit 1:
Want to mention that there might be almost 50 people names in these columns. And each row would represent response from one examiner doing the survey. There will be about 100 such examiners and hence about 100 rows.
Here is my solution, i am messing with PHP more, so my answer will be by PHP side, if you want SQL solution, you should wait for some time to let another user add SQL side solution,
You will get this kind of array in PHP from MySQL,
$result = [
'c1_1'=>['red','black','cyan'],
'c1_2'=>['blue','pink','red'],
'c1_3'=>['pink','plum','blue'],
'c2_1'=>['cyan','red','blue'],
'c2_2'=>['red','blue','pink'],
'c2_3'=>['gray','gray','plum']
];
Now, generate an users array having each user's achievements in each category,
$users = [];
foreach($result as $k => $v)
{
foreach($v as $user)
{
$users[$user][] = $k;
}
}
Now, $users array will look like,
array (size=7)
'red' =>
array (size=4)
0 => string 'c1_1' (length=4)
1 => string 'c1_2' (length=4)
2 => string 'c2_1' (length=4)
3 => string 'c2_2' (length=4)
'black' =>
array (size=1)
0 => string 'c1_1' (length=4)
'cyan' =>
array (size=2)
0 => string 'c1_1' (length=4)
1 => string 'c2_1' (length=4)
'blue' =>
array (size=4)
0 => string 'c1_2' (length=4)
1 => string 'c1_3' (length=4)
2 => string 'c2_1' (length=4)
3 => string 'c2_2' (length=4)
'pink' =>
array (size=3)
0 => string 'c1_2' (length=4)
1 => string 'c1_3' (length=4)
2 => string 'c2_2' (length=4)
'plum' =>
array (size=2)
0 => string 'c1_3' (length=4)
1 => string 'c2_3' (length=4)
'gray' =>
array (size=2)
0 => string 'c2_3' (length=4)
1 => string 'c2_3' (length=4)
Now, define a function to calculate marks, by passing the array by user we just generated,
function marks_of($input)
{
$marks_index = ['_1'=>3, '_2'=>2, '_3'=>1]; // define marks here
$marks = 0;
foreach($input as $marking)
{
$marks += $marks_index[substr($marking, -2)];
}
return $marks;
}
You need to define marks in each category as i commented in the above code.
Now, use it like,
$marks_of_red = marks_of($users['red']);
will give
int 10
To generate an array having each user's marks by name,
$all_users_marks = [];
foreach($users as $name => $achievements)
{
$all_users_marks[$name] = marks_of($users[$name]);
}
Now, $all_users_marks is
array (size=7)
'red' => int 10
'black' => int 3
'cyan' => int 6
'blue' => int 8
'pink' => int 5
'plum' => int 2
'gray' => int 2
As i already said, wait for someone if you want MySQL sided answer.
Normalize the table like this:
question | rank | name
Then use this query to get the total scores:
SELECT name, SUM( 4 - rank ) score FROM mytable GROUP BY name ORDER BY score DESC
I'm looking to use the results in an array and sort them using a ranking algorithm similar to say Hacker News or Reddit.
For example, paraphrasing the HN algorithm:
Score = P / (T+2)^G
where,
P = points of an item (e.g. votes + comments + likes)
T = time since submission (in hours)
G = Gravity, (on HN defaults to 1.8)
From what I understand, I need to use a PHP sorting array, but the PHP manual is confusing, and the similar answers on StackOverflow have very specific answers without many comments as to what the function is doing. e.g. here, here & here.
My data looks as follows
Array
(
[0] => Array
(
[post_created] => 2011-12-12 07:18:17
[post_num_likes] => 1
[post_num_comments] => 0
[post_message] => Some message
[votes] => 16
)
[1] => Array
(
[post_created] => 2011-12-11 22:17:16
[post_num_likes] => 0
[post_num_comments] => 4
[post_message] => Another message
[votes] => 21
)
[2] => Array
(
[post_created] => 2011-12-11 20:21:11
[post_num_likes] => 1
[post_num_comments] => 2
[post_message] => Next message
[votes] => 1
)
[3] => Array
(
[post_created] => 2011-12-11 20:11:47
[post_num_likes] => 0
[post_num_comments] => 0
[post_message] => Something else
[votes] => 0
)
[4] => Array
(
[post_created] => 2011-12-11 20:09:46
[post_num_likes] => 1
[post_num_comments] => 0
[post_message] => Another message
[votes] => 5
)
So far as I understand, I need to do something like the following:
// Send array as 2nd parameter due to way you call functions in CodeIgniter
uksort($array, array('Class_name','postrank'));
function postrank($a, $b) {
// some sorting function here
return strcmp($a, $b);
}
I've tried copying and pasting various functions, but as they're not so well commented, it's hard to know what's going on.
How might I go about recreating a similar post ranking sorting function with the above data?
amidoinitrite?
SELECT * , (
votes + post_num_comments + post_num_likes - 1
) / POW( ROUND( (
TIME_TO_SEC( TIMEDIFF( NOW( ) , post_created ) ) / 3600 ) + 2 ) , 1.8
) AS score
FROM hacker_news
ORDER BY score DESC
The formula on website is actually: Score = (P-1) / (T+2) ^ G
My example code for PHP older than 5.3 :)
<?php
function customSort($a, $b){
foreach(array('a', 'b') as $vn){
$tmp = $$vn;
$p = $tmp['post_num_likes'] + $tmp['post_num_comments'] + $tmp['votes'];
$t = ceil((time() - strtotime($tmp['post_created'])) / 3600);
$$vn = $p / pow($t + 2, 1.81);
}
return $a - $b;
}
usort($array, 'customSort');
var_dump($array);
$score = function($arr) {
extract($arr);
return ($votes + $comments + $likes) / pow($created_time + 2, 1.8);
};
usort($array, function($a, $b) use ($score) {
return $score($a) - $score($b);
});
This needs php 5.3 because I used anonymous functions.