Grouping data and presenting in a table from an api - php

I am returning data in a for each loop in 2 strings from an api like this:
eg $key = "2012 q4"; and $value = "34542";
*2012 q4* **34542**
*2012 q3* **35383**
*2012 q2* **36171**
*2012 q1* **36926**
*2011 q4* **37913**
*2011 q3* **38740**
*2011 q2* **39641**
*2011 q1* **40548**
I would then like to display it in this format in a table
year q1 q2 q3 q4
2012 36926 36171 35383 34542
2011 40548 39641 38740 37913
This is all I have so far, literally clueless on how to go from here.
foreach($hm["quarterly_tax"]["licensed"] as $key => $value) {
echo $key." ".$value."<br />";
}
I could work out the year and quarter by doing this I guess:
$year = substr($key, 0, 4);
$quater = substr($key, 5, 7);
but stuck from then on...
Any help would be appreciated

Have not tested it, but should give you the some idea for the logic.
foreach($hm["quarterly_tax"]["licensed"] as $key => $value) {
$year = substr($key, 0, 4);
$quater = substr($key, 5, 7);
$arr[$year][$q][] = $value;
}
Now you will have an 3d array that's sorted per possible values, should be something like this : `
Array
(
[2012] => Array
(
[q1] => Array
(
[0] => 36926
[1] => 12345
)
[q2] => Array
(
[0] => 36171
)
[q3] => Array
(
[0] => 35383
)
)
[2011] = Array
(
[q1] = Array
(
[0] =40548
)
)
)
Which is much easier to handle, since it's sorted to the way you need it, now u can just output the table accordingly.

Related

Merge two multidimensional arrays into one in Php

Hi I have two multidimensional arrays in PhP and I am trying to create a new array which is flatter.
The first array is called weeksBooked and has a structure like below:
Array
(
[0] => Array
(
[periodweekno] => 27
)
[1] => Array
(
[periodweekno] => 28
)
[2] => Array
(
[periodweekno] => 29
)
)
The second one is called bookings . This stores the day a child was booked for that particular week.
Array
(
[0] => Array
(
[periodDayName] => Monday
)
[1] => Array
(
[periodDayName] => Tuesday
)
[2] => Array
(
[periodDayName] => Thursday
)
[3] => Array
(
[periodDayName] => Friday
)
)
I am trying to merge both the arrays and check if the perioddayName is Monday then in the "new" merged array I can show it as "monday"=> 0 and if not then show it as "monday"=> 1. I would like to repeat it for each "workday (i.e. monday - friday).
I apologise in advance if I am not explaining it well but this is what I am trying to achieve is a structure that I can bind to a table:
{Weekno:27, Monday:1,Tuesday:0,Wednedsay:1,Thursday:1,Friday:0
Weekno:28, Monday:0,Tuesday:0,Wednesday:1, Thursday:0,Friday:1}
This is my attempt so far but I just can't get it to flatten it :
$result = array();
foreach ($weeksbooked as $week) {
$sql = "SELECT periodDayName FROM Attendance WHERE weekno = ". $week['periodweekno'];
$bookings = $this->db->RawQuery($sql,null);
// print_r($bookings);
foreach ($bookings as $booking) {
$daysbooked= array();
if($booking['periodDayName'] == 'Monday'){
$daysbooked['monday'] = 0;
}else{
$daysbooked['monday'] = 1;
}
if($booking['periodDayName'] == 'Tuesday'){
$daysbooked['tuesday'] = 0;
}else{
$daysbooked['tuesday'] = 1;
}
.....
array_push($weeksbooked,$daysbooked)
}
array_push($result,$weekbooked)
Perhaps something like this?
$result = array();
foreach ($weeksbooked as $week) {
$sql = "SELECT periodDayName FROM Attendance WHERE weekno = ". $week['periodweekno'];
$bookings = $this->db->RawQuery($sql,null);
// print_r($bookings);
$thisweek = array('Weekno' => $week['periodweekno'],
'Monday' => 0,
'Tuesday' => 0,
'Wednesday' => 0,
'Thursday' => 0,
'Friday' => 0
);
foreach ($bookings as $booking) {
$thisweek[$booking['periodDayName']] = 1;
}
$result[] = $thisweek;
}
print_r($result);
It should produce an output something like what you are looking for. Without the raw data in a table it's hard to be certain.

Add up the values of multiple occurrences of multiple strings in a multidimensional array in PHP

I've got a multidimensional array.
I need a way to tally up the total value when both the 1st and second strings in the array occur multiple times.
So for instance :
Gold Metallic = 22
Black Toscano = 26
etc...
Any ideas?
[0] => Array
(
[0] => Array
(
[0] => Black
[1] => Toscano
[2] => 14
)
[1] => Array
(
[0] => Gold
[1] => Metallic
[2] => 10
)
)
[1] => Array
(
[0] => Array
(
[0] => Gold
[1] => Metallic
[2] => 12
)
[1] => Array
(
[0] => Black
[1] => Toscano
[2] => 12
)
)
This just solves the problem for your data structure so you have to make sure that, in practice, every two items you will get a number. Hope you can learn something from this :)
$products = array(
array(
array("Black", "Toscano", 14),
array("Gold", "Metallic", 10)
),
array(
array("Black", "Toscano", 12),
array("Gold", "Metallic", 12)
),
);
$accumulated = array();
$key = "";
$callback = function($item, $index) use(&$key, &$accumulated) {
if($index != 2) {
$key .= $item;
} else {
if(!array_key_exists($key, $accumulated)) {
$accumulated[$key] = 0;
}
$accumulated[$key] += $item;
$key = "";
}
};
array_walk_recursive($products, $callback);
var_dump($accumulated);
Should be a simple case of looping over the data and storing an array of sums. This is one possibility using a hash with keys as the pairs concatenated with a separator sentinel value.
$separator = "||"; //take care to choose something that doesn't pop up in your data here
//$data = example data;
$pairs = array();
foreach ($data as $val) {
foreach ($val as $pair) {
$str = $pair[0] . $separator . $pair[1];
if (array_key_exists($str, $pairs))
$pairs[$str] += $pair[2];
else
$pairs[$str] = $pair[2];
}
}
print_r($pairs);
output:
["Black||Toscano"] => 26,
["Gold||Metallic"] => 22
The data can be easily retrieved at this point
foreach ($pairs as $str => $sum) {
$str = explode($separator, $str);
echo $str[0] . ", " . $str[1] . ": " . $sum;
}

put values from query into array

I need values from my database to plot a graph.
I have multiple lines I want to plot on the same graph.
I need the values, for each line, in the following form, for as many different $dates there are in the database:
$graph_points1 = array(array($date, $value), array($date, $value), array($date, $value));
I have a query to get the data from the database:
$data = $wpdb->get_results($wpdb->prepare( "SELECT * FROM `wp_graph_info` ORDER BY DATE ASC"));
If I use the following code:
foreach($data as $datas){
$list_name = $datas->list_name;
$date = $datas->date;
$value = $datas->subscriber_count;
if($list_name == 'line1'){
$result = array(array($date,$value));}}
print_r($result); will give:
Array ( [0] => Array ( [0] => 2015-05-16 [1] => 131 ) )
Array ( [0] => Array ( [0] => 2015-05-17 [1] => 133 ) )
Array ( [0] => Array ( [0] => 2015-05-18 [1] => 137 ) )
which is almost what I want.
I need to have the results as:
$graph_points1 = array(array(2015-05-16, 131), array(2015-05-17, 133), array(2015-05-18, 137));
how to I put it in the above form?
Also I can't plot the date on the x-axis. How do I only retrieve the 'day' value so I have:
$graph_points1 = array(array(16, 131), array(17, 133), array(18, 137));
Also if there a way to loop through all th $list_names (I have 7 different lists, so my graph will plot 7 lines) or do I need to use an if() statement for each one?
$result = [];
foreach($data as $datas){
$list_name = $datas->list_name;
$date = $datas->date;
$value = $datas->subscriber_count;
list($year, $month, $day) = explode('-', $date);
$result[$list_name][] = array($day,$value);
}
echo "<pre>";var_dump($result);echo "</pre>";

Sum of columns in multidimensional array without loops

I'm used to analysing data in R and have a hard time figuring out array in PHP.
Given the following array ($dat), what is the easiest way to get the total number of all females?
print("<pre>".print_r($dat,true)."</pre>");
Array
(
[0] => Array
(
[0] => female
[1] => blue
[2] => 62
)
[1] => Array
(
[0] => female
[1] => red
[2] => 22
)
[2] => Array
(
[0] => male
[1] => blue
[2] => 21
)
)
I'm doing this:
foreach($dat as $row) {
if($row[0]=='female') {
$females = $females + $row[2];
}
}
But there must be a way without loops!
Isn't there something like sum($dat[][2])?
Result for this sample should be 84
It seems I misinterpreted your question...
To obtain the sum, you can use array_reduce instead of a foreach loop (although it's not going to be much of an improvement):
array_reduce($dat, function($prev,$curr){return $prev+($curr[0]==='female'?$curr[2]:0);}, 0);
To obtain the number of elements containing 'female', You could use count with array_filter:
echo count(array_filter($dat, function($x){return in_array('female', $x);}));
This filters the array for any sub-arrays that contain the string female and returns the number of elements.
If you're sure that the string 'female' is always the zeroth element of the array, you could simplify the function slightly:
echo count(array_filter($dat, function($x){return $x[0]==='female';}));
You can array_reduce your array to a sum that way :
$array[0] = array('female', 2);
$array[1] = array('female', 5);
$array[2] = array('male', 2);
$sum = array_reduce($array, function ($value, $item) {
if ($item[0] == 'female') $value += $item[1];
return $value;
}, 0);
var_dump($sum);
Output :
7

How to calculate/generate a string with all possible values in an array?

This is driving me nuts but I've been struggling with this all noon now (im in GMT+2;)).
I want to do a fairly (I believed but realized it turned out otherwise..) simple task.
Lets say I have an array which looks like this:
Array
(
[0] => Array
(
[OptionID] => 8748
[Values] => Array
(
[0] => 11614
[1] => 11615
)
)
[1] => Array
(
[OptionID] => 8749
[Values] => Array
(
[0] => 11616
[1] => 11617
)
)
)
This array is for generating all possible options with a product. Lets say OptionID 8748 means 'Size' and the Values in that array are 'L' & 'XL'. OptionID 8749 could be 'Color' with Values 'Red' and 'Black'.
I want to achieve the simple task to get the four unique combinations of that product in a string like:
11614+11616
11614+11617
11615+11616
11615+11617
But then, with a different product there could be a third product option, so it should be able to work arround with an unlimited depth.
basically
$result = array_cartesian(array_pluck($a, 'Values'));
and here are the helper functions:
function array_pluck($a, $key) {
$r = array();
foreach($a as $v)
$r[] = $v[$key];
return $r;
}
function array_cartesian($_) {
if(count($_) == 0)
return array(array());
$a = array_shift($_);
$c = array_cartesian($_);
$r = array();
foreach($a as $v)
foreach($c as $p)
$r[] = array_merge(array($v), $p);
return $r;
}

Categories