How to create json data from multidimension array (each month in year) - php

I need to export a set of json data for highchart. But I'm having a problem with looping.
I've got 2 set of arrays:
Years Array (2015,2014,2013,2012) - form MySQL
Month Array (01,02,03,04,05,06,07,08,09,10,11,12)
So I make it in array - multidimensional. With this code.
$sql_arrYr=mysqli_query($con,"select year(bk_date1) as arrYr from booking_db group by year(bk_date1) order by arrYr asc");
while($rec_arrYr=mysqli_fetch_array($sql_arrYr)){
$arrYr[$rec_arrYr['arrYr']]=array("01","02","03","04","05","06","07","08","09","10","11","12");
}
Then I've got:
Array ( [2015] => Array ( [0] => 01 [1] => 02 [2] => 03 [3] => 04 [4] => 05 [5] => 06 [6] => 07 [7] => 08 [8] => 09 [9] => 10 [10] => 11 [11] => 12 )...);
Which is looking good coz I have all data I need in a set of arrays - year and each month values.
So I continue with fetching data from mySQL with this code.
foreach($arrYr as $key=>$val){
$rows=array();
$rows[type]='spline';
$rows[name]=$key;
foreach($val as $mon){
$sql_nBk=mysqli_query($con,"select count(*) as nBkr from booking_db where year(bk_date1)='$key' and month(bk_date1)='$mon'");
$rec_nBk=mysqli_fetch_array($sql_nBk);
$rows[data][]=$rec_nBk['nBkr'];
}
}
echo json_encode($rows);
The problem happened here. It's not loop. The only line I've got is.
{"type":"spline","name":2015,"data":["9","8","0","0","0","0","0","0","0","0","0","0"]}
Which I expect this:
{"type":"spline","name":2015,"data":["9","8","0","0","0","0","0","0","0","0","0","0"]}
{"type":"spline","name":2014,"data":["9","8","0","0","0","0","0","0","0","0","0","0"]}
{"type":"spline","name":2013,"data":["9","8","0","0","0","0","0","0","0","0","0","0"]}
{"type":"spline","name":2012,"data":["9","8","0","0","0","0","0","0","0","0","0","0"]}
Please give me a reason why it's not loop. Even I put them in a right loop.

You are setting $rows to an empty array each time through the outer loop. Also, you can't have duplicate keys. The first type is overwritten by the next (also name and data) so you have to make it multidimensional. You can use the $key variable for this to make it easy, or implement a counter $i and use $i++ or something.
$i = 0;
foreach($arrYr as $key=>$val){
$rows[$i]['type']='spline';
$rows[$i]['name']=$key;
foreach($val as $mon){
$sql_nBk=mysqli_query($con,"select count(*) as nBkr from booking_db where year(bk_date1)='$key' and month(bk_date1)='$mon'");
$rec_nBk=mysqli_fetch_array($sql_nBk);
$rows[$i]['data'][]=$rec_nBk['nBkr'];
}
$i++;
}
echo json_encode($rows);

Related

usort of session array not outputting as expected

I have a grid of img squares that can be dragged into any order using the sortable library. Each img is a visual representation of a result from a mySQL db query that selects any image that shares an 'imageparent' identifier. The order they're presented in the grid is taken from the 'imageorder' column in the database and starts at 0 and works in sequence up to the nth number of images returned.
The purpose of dragging the img grid is to be able to change the 'imageorder' index. On completion of the drag, the sortable library POSTS an 'imageorder' var by ajax to service.php and is received correctly. So rather than the original 0,1,2,3,4,5,6,7 order of the original, it sends a string like 2,1,0,3,4,5,7,6. Not too hard to grasp. After I switch the order the orderList var sent to service.php is always correct, but the array I end up sending to the db and setting as my session var becomes a little garbled in order after the second or third drag and I'm not quite sure why.
Code Examples and Comments
$_SESSION['selectedCsImages'] Array structure:
[0] => Array
(
[imagename] => "Title"
[imageorder] => 0
[imageid] => 43
)
[1] => Array
(
[imagename] => "Title"
[imageorder] => 1
[imageid] => 21
)
[2] => Array
(
[imagename] => "Title"
[imageorder] => 2
[imageid] => 3
)
etc...
Services.php extract:
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
// Turn the orderList posted into an array
$removeChars = array('"','[',']');
$orderList = str_replace($removeChars, "", $_POST['order']); // POST received fine.
$listArray = explode(",",$orderList);
// Retrieve the session array
$sorting = $_SESSION['selectedCsImages'];
/* My logic is that I compare the $sorting array to $listArray and reorder $sorting by 'imageorder' to match $listarray */
usort($sorting, function($a, $b) use ($listArray) {
return array_search($a['imageorder'], $listArray) - array_search($b['imageorder'], $listArray);
});
/* I now have a $sorting array that (sometimes, hence the problem) matches the order that the images had just been dragged into by the user. Typically, as I mentioned above, it's correct after the first drag, but not always after the second or third where it creates a new order that I can't see a pattern or logic in. */
/* Had there not been errors with the usort function, I (would) have a $sorting array in the order I want but with imageorder values referring to pre-sorting. I iterate through the array and set each key to 0, 1, 2, etc. so that I have an array in the correct order and with each imageorder correctly stating its place.*/
$i = 0;
foreach ($sorting as $key => $value) {
$sorting[$key]['imageorder'] = $i;
$i++;
}
/* The information is attempted to be sent to the db and, on success I update the session var */
// Database code (runs succesfully and updates the db as per the image orders found in the $sorting array)
$_SESSION['selectedCsImages'] = $sorting;
Debugging:
From debugging, it appears that something happens with the usort function when I call this page from ajax for the second or third time. Everything after this follows through fine and processes the correct or incorrect order as per expectations. The orderList var posted by sortable is correct each time. I'd provide a sample of the $sorted var after usort each time but it's as simple to describe it as the above array example in an order I didn't specify after dragging and I can't see a pattern in the seemingly random order it outputs.
From researching, I had thought that it was an issue with session vars being retained until the page is refreshed but it appears that the ajax call to services.php should refresh the $_SESSION['selectedCsImages'] var. I had also read that, perhaps, I was unknowingly using referenced array values and - as I source from a session var to a new array and, ultimately, save back to this session var from this array - I may have created some messy referencing feedback. However, I tried using $sorted = (array)clone(object)$_SESSION['selectedCsImages']; before attempting usort and the results didn't change.
PHP error logs are showing nothing.
Updates:
Per the suggestion of #Ayaou, I've checked the output of $listArray and am getting some unexpected results. I'd wrongly assumed that as the posted $orderList was correct, that the exploded array would not be a culprit.
Here's the output of print_r($listArray) after completing the following order swaps of 16 img elements: 1st with 2nd, 2nd last with last,6th with 7th:
1st and 2nd:
(
[0] => 1
[1] => 0
[2] => 2
[3] => 3
[4] => 4
[5] => 5
[6] => 6
[7] => 7
[8] => 8
[9] => 9
[10] => 10
[11] => 11
[12] => 12
[13] => 13
[14] => 14
[15] => 15
)
last and 2nd last:
(
[0] => 1
[1] => 0
[2] => 2
[3] => 3
[4] => 4
[5] => 5
[6] => 6
[7] => 7
[8] => 8
[9] => 9
[10] => 10
[11] => 11
[12] => 12
[13] => 13
[14] => 15
[15] => 14
)
6th with 7th:
(
[0] => 1
[1] => 0
[2] => 2
[3] => 3
[4] => 4
[5] => 6
[6] => 5
[7] => 7
[8] => 8
[9] => 9
[10] => 10
[11] => 11
[12] => 12
[13] => 13
[14] => 15
[15] => 14
)
I was progressing with the idea that $listArray would show a sequential 0,1,2,3,etc. each time with only the two swapped items showing order changes. As it's not, I'll look back again at $orderList and check if my sortable library is updating the orders it's obtaining correctly from the updated session var. Older order swaps are being retained somewhere along the chain where they shouldn't.
The solution is on your sortable form (on the front end), so instead of sending the imageorder on your 'order' post data, send the imageid index.
Then change your sort callback like this
//Use imageid index instead of imageorder
usort($sorting, function($a, $b) use ($listArray) {
return array_search($a['imageid'], $listArray) - array_search($b['imageid'], $listArray);
});

loop through multidimensional array and order sub-array by scores

I am trying to calculate the winning order of golfers when they are tied in a competition.
These golf competitions are using the "stableford" points scoring system, where you score points per hole with the highest points winning. Compared to normal golf "stroke play" where the lowest score wins (though this also has the countback system, only calculating the lowest score in the event of a tie...)
The rules are to use a "countback". i.e., if scores are tied after 9 holes, the best placed of the ties is the best score from the last 8 holes. then 7 holes, etc.
The best I can come up with is 2 arrays.
An array with all the players who tied in a given round. ($ties)
One which has the full score data in (referencing the database playerid) for all 9 holes. ($tie_perhole)
I loop through array 1, pulling data from array 2 and using the following formula to create a temporary array with the highest score:
$max = array_keys($array,max($array));
If $max only has 1 item, this player is the highest scorer. the loop through the first array is "by reference", so on the next iteration of the loop, his playerid is now longer in the array, thus ignored. this continues until there is only 1 playerid left in the first array.
However, it only works if a single player wins in each iteration. The scenario that doesn't work is if a sub-set of players tie on any iterations / countbacks.
I think my problem is the current structure I have will need the original $ties array to become split, and then to continue to iterate through the split arrays in the same way...
As an example...
The $ties array is as follows:
Array
(
[18] => Array
(
[0] => 77
[1] => 79
[2] => 76
[3] => 78
)
)
The $tie_perhole (score data) array is as follows:
Array
(
[18] => Array
(
[77] => Array
(
[9] => 18
[8] => 16
[7] => 14
[6] => 12
[5] => 10
[4] => 8
[3] => 6
[2] => 4
[1] => 2
)
[79] => Array
(
[9] => 18
[8] => 17
[7] => 15
[6] => 14
[5] => 11
[4] => 9
[3] => 7
[2] => 5
[1] => 3
)
[76] => Array
(
[9] => 18
[8] => 16
[7] => 14
[6] => 12
[5] => 10
[4] => 8
[3] => 6
[2] => 4
[1] => 2
)
[78] => Array
(
[9] => 18
[8] => 17
[7] => 15
[6] => 13
[5] => 11
[4] => 9
[3] => 7
[2] => 5
[1] => 3
)
)
)
So in this competition, player's 78 and 79 score highest on the 8th hole countback (17pts), so 1st and 2nd should be between them. Player 79 should then be 1st on the 6th hole countback (14pts, compared to 13pts). The same should occur for 3rd and 4th place with the 2 remaining other players.
There are other scenarios that can occur here, in that within a competition, there will likely be many groups of players (of different amounts) on different tied points through the leaderboard.
Also note, there will be some players on the leaderboard who are NOT tied and stay in their current outright position.
The basics of the working code I have is:
foreach ($ties as $comparekey => &$compareval) {
$tie_loop = 0;
for ($m = 9; $m >= 1; $m--) {
$compare = array();
foreach ($compareval as $tie) {
$compare[$tie] = $tie_perhole[$comparekey][$tie][$m];
}
$row = array_keys($compare,max($compare));
if (count($row) == 1) {
$indexties = array_search($row[0], $ties[$comparekey]);
unset($ties[$comparekey][$indexties]);
// Now update this "winners" finishing position in a sorted array
// This is a multidimensional array too, with custom function...
$indexresults = searchForId($row[0], $comp_results_arr);
$comp_results_arr[$indexresults][position] = $tie_loop;
$tie_loop++;
}
// I think I need conditions here to filter if a subset of players tie
// Other than count($row) == 1
// And possibly splitting out into multiple $ties arrays for each thread...
if (empty($ties[$comparekey])) {
break;
}
}
}
usort($comp_results_arr, 'compare_posn_asc');
foreach($comp_results_arr as $row) {
//echo an HTML table...
}
Thanks in advance for any helpful insights, tips, thoughts, etc...
Robert Cathay asked for more scenarios. So here is another...
The leaderboard actually has more entrants (player 26 had a bad round...), but the code i need help with is only bothered about the ties within the leaderboard.
Summary leaderboard:
Points Player
21 48
21 75
20 73
20 1
13 26
This example produces a $tie_perhole array of:
Array
(
[21] => Array
(
[75] => Array
(
[9] => 21
[8] => 19
[7] => 16
[6] => 14
[5] => 12
[4] => 9
[3] => 7
[2] => 5
[1] => 3
)
[48] => Array
(
[9] => 21
[8] => 19
[7] => 16
[6] => 13
[5] => 11
[4] => 9
[3] => 8
[2] => 5
[1] => 3
)
)
[20] => Array
(
[73] => Array
(
[9] => 20
[8] => 18
[7] => 16
[6] => 13
[5] => 11
[4] => 8
[3] => 6
[2] => 5
[1] => 3
)
[1] => Array
(
[9] => 20
[8] => 17
[7] => 16
[6] => 14
[5] => 12
[4] => 9
[3] => 7
[2] => 4
[1] => 2
)
)
)
In this example, the array shows that players 75 and 48 scored 21 points that player 75 will eventually win on the 6th hole countback (14pts compared to 13pts) and player 48 is 2nd. In the next tied group, players 73 and 1 scored 20 points, and player 73 will win this group on the 8th hole countback and finishes 3rd (18 pts compared to 17 pts), with player 1 in 4th. player 26 is then 5th.
Note, the $tie_loop is added to another array to calculate the 1st to 5th place finishing positions, so that is working.
Hopefully that is enough to help.
Ok, so I don't understand golf at all... hahaha BUT! I think I got the gist of this problem, so heres my solution.
<?php
/**
* Author : Carlos Alaniz
* Email : Carlos.glvn1993#gmail.com
* Porpuse : Stackoverflow example
* Date : Aug/04/2015
**/
$golfers = [
"A" => [1,5,9,1,1,2,3,4,9],
"B" => [2,6,4,2,4,4,1,9,3],
"C" => [3,4,9,8,1,1,5,1,3],
"D" => [1,5,1,1,1,5,4,5,8]
];
//Iterate over scores.
function get_winners(&$golfers, $hole = 9){
$positions = array(); // The score numer is the key!
foreach ($golfers as $golfer=>$score ) { // Get key and value
$score_sub = array_slice($score,0,$hole); // Get the scores subset, first iteration is always all holes
$total_score = (string)array_sum($score_sub); // Get the key
if(!isset($positions[$total_score])){
$positions[$total_score] = array(); // Make array
}
$positions[$total_score][] = $golfer; // Add Golpher to score.
}
ksort($positions, SORT_NUMERIC); // Sort based on key, low -> high
return array(end($positions), key($positions)); // The last shall be first
}
//Recursion is Awsome
function getWinner(&$golfers, $hole = 9){
if ($hole == 0) return;
$winner = get_winners($golfers,$hole); // Get all ties, if any.
if(count($winner[0]) > 1){ // If theirs ties, filter again!
$sub_golfers =
array_intersect_key($golfers,
array_flip($winner[0])); // Only the Worthy Shall Pass.
$winner = getWinner($sub_golfers,$hole - 1); // And again...
}
return $winner; // We got a winner, unless they really tie...
}
echo "<pre>";
print_R(getWinner($golfers));
echo "</pre>";
Ok... Now ill explain my method...
Since we need to know the highest score and it might be ties, it makes no sense to me to maintain all that in separate arrays, instead I just reversed the
golfer => scores
to
Tota_score => golfers
That way when we can sort the array by key and obtain all the golfers with the highest score.
Now total_score is the total sum of a subset of the holes scores array. So... the first time this function runs, it will add all 9 holes, in this case theres 3 golfers that end up with the same score.
Array
(
[0] => Array
(
[0] => A
[1] => B
[2] => C
)
[1] => 35
)
Since the total count of golfers is not 1 and we are still in the 9th hole, we run this again, but this time only against those 3 golfers and the current hole - 1, so we are only adding up to the 8th hole this time.
Array
(
[0] => Array
(
[0] => B
[1] => C
)
[1] => 32
)
We had another tie.... this process will continue until we reach the final hole, or a winner.
Array
(
[0] => Array
(
[0] => C
)
[1] => 31
)
EDIT
<?php
/**
* Author : Carlos Alaniz
* Email : Carlos.glvn1993#gmail.com
* Porpuse : Stackoverflow example
**/
$golfers = [
"77" => [2,4,6,8,10,12,14,16,18],
"79" => [3,5,7,9,11,14,15,17,18],
"76" => [2,4,6,8,10,12,14,16,18],
"78" => [3,5,7,9,11,13,15,17,18]
];
//Iterate over scores.
function get_winners(&$golfers, $hole = 9){
$positions = array(); // The score numer is the key!
foreach ($golfers as $golfer => $score) { // Get key and value
//$score_sub = array_slice($score,0,$hole); // Get the scores subset, first iteration is always all holes
$total_score = (string)$score[$hole-1]; // Get the key
if(!isset($positions[$total_score])){
$positions[$total_score] = array(); // Make array
}
$positions[$total_score][] = $golfer; // Add Golpher to score.
}
ksort($positions, SORT_NUMERIC); // Sort based on key, low -> high
return [
"winner"=> end($positions),
"score" => key($positions),
"tiebreaker_hole" => [
"hole"=>$hole,
"score"=> key($positions)],
]; // The last shall be first
}
//Recursion is Awsome
function getWinner(&$golfers, $hole = 9){
if ($hole == 0) return;
$highest = get_winners($golfers,$hole); // Get all ties, if any.
$winner = $highest;
if(count($winner["winner"]) > 1){ // If theirs ties, filter again!
$sub_golfers =
array_intersect_key($golfers,
array_flip($winner["winner"])); // Only the Worthy Shall Pass.
$winner = getWinner($sub_golfers,$hole - 1); // And again...
}
$winner["score"] = $highest["score"];
return $winner; // We got a winner, unless they really tie...
}
echo "<pre>";
print_R(getWinner($golfers));
echo "</pre>";
Result:
Array
(
[winner] => Array
(
[0] => 79
)
[score] => 18
[tiebreaker_hole] => Array
(
[hole] => 6
[score] => 14
)
)

Transpose query result set [duplicate]

This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Chunk and transpose a flat array into rows with a specific number of columns
(3 answers)
Closed 5 months ago.
So I have a database with players names and their skill level.
It looks like this:
Id | Name | Level
1 | Peter | 24
2 | Andy | 23
...
24 | John | 1
The first player in the list with the highest level is the strongest one, and the last is the weakest.
I need to sort them in groups with 4 players, so if I have 24 people there will be 6 groups.
The way I need to sort it I call "zig-zag".
It goes like this:
Ag Bg Cg Dg Eg Fg
01 02 03 04 05 06
12 11 10 09 08 07
13 14 15 16 17 18
24 23 22 21 20 19
So the A group will consist of players: 1, 12, 13, 24.
B group of players: 2, 11, 14, 23.
C group of players: 3, 10, 15, 22 and so on.
It's easy to do it by hand, but how I could automate this sort with PHP language?
The groups should be array list (I think so) which could I easily put to the group tables in database.
The idea would be to:
Sort your starting data (or preferably, start with it sorted).
Split it into chunks, basically one per each of your rows.
Reverse the order of every other chunk.
Flip the matrix so you've got your groups - one per column instead of one per row.
Example:
// Basic sample data.
$players = range(1, 24);
// Sort them ascending if you need to.
sort($players);
// Make a matrix. 2d array with a column per group.
$matrix = array_chunk($players, ceil(count($players)/4));
// Reverse every other row.
for ($i = 0; $i < count($matrix); $i++) {
if ($i % 2) {
$matrix[$i] = array_reverse($matrix[$i]);
}
}
// Flip the matrix.
$groups = array_map(null, ...$matrix); // PHP 5.6 with the fancy splat operator.
//$groups = call_user_func_array('array_map', array_merge([null], $matrix)); // PHP < 5.6 - less fancy.
// The result is...
print_r($groups);
Output:
Array
(
[0] => Array
(
[0] => 1
[1] => 12
[2] => 13
[3] => 24
)
[1] => Array
(
[0] => 2
[1] => 11
[2] => 14
[3] => 23
)
[2] => Array
(
[0] => 3
[1] => 10
[2] => 15
[3] => 22
)
[3] => Array
(
[0] => 4
[1] => 9
[2] => 16
[3] => 21
)
[4] => Array
(
[0] => 5
[1] => 8
[2] => 17
[3] => 20
)
[5] => Array
(
[0] => 6
[1] => 7
[2] => 18
[3] => 19
)
)

PHP Arrays duplicating?

I am trying to code a cron job so if a code in the database and is unused and older then 72 hours it drops the row in the database.
The problem I am having however is that when I am trying to get the array data in a row, so I can run an 'If statement' and then the drop command, when printing the array I get duplicates like as follows
33520891520891do not usedo not use----aaron hattonaaron hattonSunday 8th of September 2013 12:46:20 PMSunday 8th of September 2013 12:46:20 PMUnusedUnused--
My code is as follows
// Set variable for the time
$timenow = date('l jS \of F Y h:i:s A');
// Start Expired password check and drop function
function cronexec_expired ($timenow) {
include('../../config.php');
// Open up a new MySQLi connection to the MySQL database
mysql_connect($dbHost, $dbUsername, $dbPassword);
mysql_select_db($dbTable);
// Query to check the status of the code input
$expiry_check = "SELECT * FROM code_log WHERE status='Unused'";
// Run the query
$expiry_checkexec = mysql_query($expiry_check);
while($expiry_possibles = mysql_fetch_array($expiry_checkexec)) {
foreach ($expiry_possibles as $expiry_possible) {
print_r ($expiry_possible);
};
}
}
// Start Redeemed Password check and drop function
// Execute Functions
cronexec_expired ($timenow);
Any help would be really appreciated!
Edit
When removing the 'foreach' and running the following:
print_r ($expiry_possibles);
I get the following
Array ( [0] => 3 [id] => 3 [1] => 520891 [code] => 520891 [2] => do not use [refid] => do not use [3] => - [hostname] => - [4] => - [userip] => - [5] => aaron hatton [creater] => aaron hatton [6] => Sunday 8th of September 2013 12:46:20 PM [timecreated] => Sunday 8th of September 2013 12:46:20 PM [7] => Unused [status] => Unused [8] => - [timeredeemed] => - )
Am I doing something wrong?
if you mean numeric index in your array output. use mysql_fetch_assoc() instead of mysql_fetch_array()
mysql_fetch_array() essentially returns two arrays one with numeric index, one with associative string index.

PHP calculate running sum from array based on date value

I need to create a PHP function that will loop through a multi-dimensional array and return a value which represents the sum of a certain key, where the value of another key is <= the date value passed into the function. Here is a sample array of the data array:
Array
(
[Nov 18, 2011] => Array
(
[C] => 100
[I] => 100
[M] => 100
)
[Nov 22, 2011] => Array
(
[C] => 200
[I] => 200
)
[Nov 29, 2011] => Array
(
[C] => 300
[I] => -300
)
)
There will never be more than these 3 categories [C], [I] and [M] and the values for each date should be considered a running sum.
So, how do I calculate the value of the [C] category as of the Nov 22, 2011 date? The correct value is of course 300. (Being 100 from Nov 18 + 200 from Nov 22)
What if I needed to calculate the value of [I] as of Nov 29, 2011? The correct answer in this example would be 0. (Being 100 + 200 - 300)
I'm open to ideas on how best to achieve this. My instinct is to have some kind of function and then pass in the category and date values. Thanks.
Depends on how many times you're likely to want to do this and if you'll need to do it for each category, etc whether or not you use a function or just a simple loop.
Either way you could put the following into a function and just pass in $target_date and the category (replacing the hard-coded "C" I'm using for this example):
$c_total = 0;
foreach($main_array as $date => $sub_array)
{
if($date <= $target_date)
{
$c_total += $sub_array["C"];
}
}
EDIT: For clarity here's the function using strtotime() to convert the date values to timestamps for easier comparison:
function getCategoryTotal($target_date, $category)
{
$c_total = 0;
$target_date = strtotime($target_date);
foreach($main_array as $date => $sub_array)
{
if(strtotime($date) <= $target_date)
{
$c_total += $sub_array[$category];
}
}
return $c_total;
}

Categories