I am creating a leaderboard in WordPress. The user submits their mileage along with the date and method in an ACF repeater field. I am pulling the data and need to output the following $leaderboard array:
Array ( [user1] => Array ( [walking] => 2 [overall_mileage] => 11 [swimming] => 9 ) [user2] => Array ( [running] => 54.25 [overall_mileage] => 54.25 ) )
I am calculating the mileage and inserting it into the array.
What's the best way to loop through this into a table so that it displays in a leaderboard with a breakdown as follows?
USERNAME | SWIMMING | WALKING | RUNNING | OVERALL MILES
Thanks in advance
Related
I'm facing one problem and I can't find the perfect and best optimized solution.
So I'm kindly asking for your opinion.
Here's what bothering me.
I've got a serialized array from DB that looks like this:
a:6:{s:13:"property_type";s:1:"1";s:16:"property_feature";a:2:{i:0;s:1:"3";i:1;s:1:"4";}s:19:"property_offer_type";s:1:"5";s:19:"property_built_type";a:1:{i:0;s:2:"10";}s:24:"properties_office_phones";s:2:"13";s:15:"property_labels";a:1:{i:0;s:1:"8";}}
Here is the non-serialized version for more clarity:
Array(
[property_type] => 1
[property_feature] => Array
(
[0] => 3
[1] => 4
)
[property_offer_type] => 5
[property_built_type] => Array
(
[0] => 10
)
[properties_office_phones] => 13
[property_labels] => Array
(
[0] => 8
))
All of this keys values are stored in one single table.
This is how the table looks like:
ID | Name | Slug | .. etc
1 | A name here | a-name-here | .. other
What do you think will be the best and most optimized way to get the information related to those IDs using Laravel 8 relations, so it can be retrieved as relations just like "with()" is doing.
Thanks in advance!
I have trouble with some calculation in Codeigniter. Please check attached image below
https://imgur.com/HuSBkXJ
That data fetching from the database , the sale column is fine but I having trouble with monthly sale
1st day of every month sale (10) and monthly sale (10) are same, but from second day sale is correct(8), monthly sale has to be 1st day sale + second day sale(10+8 = 18). for third day sale is fine, monthly sale should be (18+20=38). the calculation going like this up to end of the month, Same process again stating from next month
How do we calculate in codeigniter, The above image i have created in excel sheet for demonstration purpose.
Model view
public function fetchSaleData()
{
$this->db->join('stock_shop','stock_shop.shop_id = stock_sale.shopId');
$this->db->join('stock_products','stock_products.product_id = stock_sale.productID');
$thisMonth=date('m');
$this->db->where('MONTH(DateOfSale)',$thisMonth);
$query= $this->db->get("stock_sale");
return $query->result_array();
}
controller view
public function salesView()
{
$data['sales']=$this->Query_sale->fetchSaleData();
$data['shops']=$this->Query_sale->fetchShop();
$this->load->view('stock/shop_sales_view',$data);
}
since you're not showing table structures or any other insight, I'll only suggest an approach based on my own code which you may feel free to adapt to your specific needs, along with the assumptions I make along the way
Assumption #1: the model returns an array in which each element contains the date and the sold units on such date
This would look like this
+-----------------+
| array data |
+------------+----+
| 2020-01-01 | 10 |
+------------+----+
| 2020-01-02 | 20 |
+------------+----+
| 2020-01-03 | 5 |
+------------+----+
| 2020-01-04 | 8 |
+------------+----+
On array form, this may look like this:
$ar = array(
0 => array(
'date' => '2020-01-01',
'units_sold' => 10,
),
1 => array(
'date' => '2020-01-02',
'units_sold' => 20,
),
2 => array(
'date' => '2020-01-03',
'units_sold' => 5,
),
3 => array(
'date' => '2020-01-04',
'units_sold' => 8,
),
);
and so on until the end of the month. Lets call the returned fields date and units_sold as in the above example
now that you have the data loaded in a variable ($ar) you can loop through it and keep tabs on the accumulated total on each loop.
$accum = 0; // keep track of accumulated total
$i = 0; // keep track of array index
foreach ($ar as $a)
{
$accum += $a['sales'];
$ar[$i]['accum'] = $accum;
$i++;
}
Upon running, this code will:
Iteration 0: For 2020-01-01, sales=10, accumulated=10
Iteration 1: For 2020-01-02, sales 20, accumulated=30
Iteration 2: For 2020-01-03, sales 5, accumulated=35
...and so on until the month is over
The above can be verified with a print_r or var_dump (I use print_r... like this: print print_r($ar,true);):
print_r output
Array
(
[0] => Array
(
[date] => 2020-01-01
[sales] => 10
[accum] => 10
)
[1] => Array
(
[date] => 2020-01-02
[sales] => 20
[accum] => 30
)
[2] => Array
(
[date] => 2020-01-03
[sales] => 5
[accum] => 35
)
[3] => Array
(
[date] => 2020-01-04
[sales] => 8
[accum] => 43
)
)
So, now that you've succesfully pushed a whole new element in your result array, you can send it over to the view and display it in tabular form as you need
I'm storing in a multi-dimensional array the progressive score of n players in different days.
So I've something like
Array
(
[0] => Array
(
[day] => 2014-10-01
[player] => John
[score] => 1500
)
[1] => Array
(
[day] => 2014-10-02
[player] => John
[score] => 1510
)
[2] => Array
(
[day] => 2014-10-01
[player] => Mary
[score] => 1400
)
[3] => Array
(
[day] => 2014-10-02
[player] => Mary
[score] => 1600
)
)
What I need a day-by-day rank for a given player, comparing his score with all other players's one, for each day.
So the input will be player's id (in this case "John") and the output should be a JSON object like
[{"day"="2014-10-01", "rank": 1}, {"day"="2014-10-02", "rank": 2}]
What's the best way to approach this problem?
To give you an idea of the dimension of my data, consider that I've the scores of 100 players in 100 different days (so I've a table of approximately 10.000 records).
EDIT (27/11/14): the multi-dimensional array is the result of a pre-processing on data stored in
a MySQL database.
This database contains information about each game played in this form:
|Date |WinnerId|LoserId|PtsEarned|PtsLost|
|2014-10-01|John |Mary |10 |-10 |
|2014-10-02|Mary |John |20 |-20 |
So I don't know If I can easily use the method suggested in the "duplicate" answer.
With my first approach, it takes about 7-8 seconds to output the result I need... so I think It's not the most efficient way to face the problem...
EDIT (28/11/14): I tried ranking data directly in MySql, and it takes about 2 seconds to give me back the ranking position of one player in a specific day; repeating the same query 100 times is a way too long process...
With a different approach I manage to create a php array with "pre-processed" data in the same time (2 seconds), but I miss the last step, i.e. how to do a rank using php functions on a multi-dimensional array (my first question). Any idea?
Questions
How should I do the query(ies) to get this results?
Should I use a different structure for database tables?
Details
I want to get results from 3 tables:
+------------------------------+-------------------+
| courses | id | <-------+
| | name | |
| | | |
+------------------------------+-------------------+ |
| sections | id | <-------|----------+
| | course_id | <- FK(courses.id) |
| | name | |
+------------------------------+-------------------| |
| resources | id | |
| | section_id | <- FK(sections.id)-+
| | name |
+------------------------------+-------------------+
I want to store results in a PHP Array like this:
Array
(
[courses] => Array
(
[id] => 1
[name] => course 1
[sections] => Array
(
[0] => Array
(
[id] => 1
[course_id] => 1
[name] => course 1 section 1
[resources] => Array
(
[0] => Array
(
[id] => 1
[section_id] => 1
[name] => resource 1
)
)
)
)
)
)
EDIT
What I did:
$cources = DB::query(Database::SELECT,
'select * from courses')->execute($db,false)[0]; // Get all courses as array
foreach($courses as &$course) {
$sections = DB::query(Database::SELECT,
'select * from sections where course_id = '.$courses['id']);
$course['sections'] = $sections;
foreach($course['sections'] as &§ion) {
$resources = DB::query(...); // Get array of resources
$section['resources'] = $resources;
}
}
The database structure is normalized - this is correct and should not be changed.
However, SQL returns de-normalized or "flattened" data for an N+ join: only a set of homogenous records can be returned in a single result-set. (Some databases, like SQL Server, allow returning structure by supporting XML generation.)
To get the desired array structure in PHP will require:
Separate queries/result-sets (as shown in the post): ick!
There will about one query/object. While the theoretical bounds might be similar, the practical implementation will be much less efficient and the overhead will be much more than for single query. Remember that every query incurs (at the very least) a round-trip penalty - as such, this is not scalable although it will likely work just fine for smaller sets of data or for "time insensitive" operations.
Re-normalize the resulting structure:
This is very trivial to do with support of a "Group By" operation, as found in C#/LINQ. I am not sure how this would be approached [easily] in PHP1. This isn't perfect either, but assuming that hashing is used for the grouping, this should be able to scale fairly well - it will definitely be better than #1.
Instead of the above, consider writing the query in such a way that the "flat" result can be used within the current problem/scope, if possible. That is, analyze how the array is to be used - then write the queries around that problem. This is often a better approach that can scale very well.
1 Related to re-normalizing the data, YMMV:
SQL result to PHP multidimensional array
PHP array to multidimensional array
Group a multidimensional array by a particular value?
You can try something like this
SELECT * FROM (
select c.id, c.name from courses c
union
select s.id, r.name,s.course_ID from sections s
union
select r.id, r.name,r.section_ID from resources r
)
You cant get multi dimensional result from mysql. The query for getting the elements should be like this:
select courses.id as coursesId,courses.name as coursesName,sections.id as sectionsId,sections.name as sectionsName,resources.id as resourcesId, resources.name as resourcesName
from courses
left join sections on courses.id=sections.course_id
left join resources on sections.id=resources.section_id;
But ofcourse it will not give you the array as you like.
if you are familiar with php then you can use this code i am writing only 2nd level you can write same way with third label
$final=array();
$c=-1;
$cid=false;
$cname=false;
$query = "SELECT c.*,s.*,r.* FROM courses AS c LEFT JOIN sections AS s ON c.id=s.course_id LEFT JOIN resources AS r ON r.section_id =s.id";
$result=mysql_query($query, $this->con) or die(mysql_error());
while($row= mysql_fetch_array($result)){
if($cid!=$row[2]){
$final['cources'][++$c]['id']=$cid=$row[0];
$final['cources'][$c]['name']=$cname=$row[1];
$s=-1;
}
$final['cources'][$c]['sections'][++$s]['id']=$row[2];
$final['cources'][$c]['sections'][$s]['course_id']=$row[3];
$final['cources'][$c]['sections'][$s]['name']=$row[4];
}
echo "<pre>";
print_r($final);
echo "</pre>";
//Outpur
Array
(
[cources] => Array
(
[0] => Array
(
[id] => 1
[name] => c1
[sections] => Array
(
[0] => Array
(
[id] => 1
[course_id] => 1
[name] => s1-1
)
[1] => Array
(
[id] => 1
[course_id] => 1
[name] => s1-1
)
)
)
[1] => Array
(
[id] => 2
[name] => c2
[sections] => Array
(
[0] => Array
(
[id] => 2
[course_id] => 2
[name] => s1-2
)
)
)
)
)
I'm trying to record some information on a database. My post looks like this:
Array
(
[Action] => 1000
[Date_Stat] => 07/02/2013
[Date_Final] => 07/02/2013
[Product_Id] => Array
(
[0] => 2
[1] => 6
[2] => 1
)
[Conversion] => Array
(
[0] => 1,20
[1] => 1,00
[2] => 2,03
)
[ValueMin] => Array
(
[0] => 2,00
[1] => 1,58
[2] => 2,70
)
[ValueMax] => Array
(
[0] => 2,50
[1] => 1,98
[2] => 2,90
)
[ValueMedio] => Array
(
[0] => 2,20
[1] => 1,68
[2] => 2,80
)
)
HOW can I insert all this on database the right way?
I'm not sure about the best way to design the tables and store the information. I'm using this to make a PRICE TABLE with starting date, final date and list all products with prices.
Also I'm thinking what is the best method. There are 2 possibilities I think about
Date_Start | Date_End |Product_Id | ValueMin | ValueMax | ValueMedio | Conversion
02-02-2013 02-03-2013 1 1.00 2.00 3.00 4.00
02-02-2013 02-03-2013 2 1.00 2.00 3.00 4.20
02-02-2013 02-03-2013 3 1.00 2.00 2.00 4.40
OR (using implode and putting all values on the same row)
Date_Start | Date_End |Product_Id | ValueMin | ValueMax | ValueMedio | Conversion
02-02-2013 02-03-2013 1,2,3 1,1,1 2, 2,2 3,3,2 4, 4.3, 4.4
Thanks a lot!
Choose the option mentioned first. Selecting Rows will become much easier if you do it that way.
To insert the records, use a simple prepared Statement (PHP Manual) and use a for-Loop.
I'd suggest a little tweak over the first option. If you create a separate table (Something along the lines of "Prices") like this:
id|DateStart|DateEnd|
1|02-02-2013|02-02-2013|
And then, in the table you suggested, you'd replace the date range for the PriceId (Foreign Key to this table). That way it'll be easier for you to maintain the consistency over changes on date ranges.