This is my array and I want to set this array in table format and I want to set first row as show below:
$_tierPrices = Array
(
Array
(
"price_qty" => "4",
"price" => "143.00",
"savePercent" => "8"
),
Array
(
"price_qty" => "12",
"price" => "133.0000",
"savePercent" => "15"
),
Array
(
"price_qty" => "20",
"savePercent" => "18",
"price" => "128.0000"
),
Array
(
"price_qty" => "40",
"savePercent" => "21",
"price" => "123.0000"
)
);
I want to set this array value in table format as shown below
This is my table row:
4 | 12 | 20 | 40 |
I need this:
4 - 11 | 12 - 19 | 20 - 39 | 40+ |
Please advise.
Try this:
Tier Price Array
<?php
$_tierPrices = array (
array
(
"price_qty" => "4",
"price" => "143.00",
"savePercent" => "8"
),
array
(
"price_qty" => "12",
"price" => "133.0000",
"savePercent" => "15"
),
array
(
"price_qty" => "20",
"savePercent" => "18",
"price" => "128.0000"
),
array
(
"price_qty" => "40",
"savePercent" => "21",
"price" => "123.0000"
)
);
?>
Tier Price Table
<table>
<tr><td>Header</td></tr>
<?php $_qtyRow = '<tr>'; ?>
<?php $_priceRow = '<tr>'; ?>
<?php $_saveRow = '<tr>'; ?>
<?php
$size = count($_tierPrices);
foreach($_tierPrices as $index => $_tierPrice) {
if($index < $size-1) {
$_qty = $_tierPrice['price_qty'] . ' - ' . ($_tierPrices[$index+1]['price_qty'] - 1);
} else {
$_qty = $_tierPrice['price_qty'] . '+';
}
$_qtyRow .= '<td>'.$_qty.'</td>';
$_priceRow .= '<td>'.$_tierPrice['price'].'</td>';
$_saveRow .= '<td>'.$_tierPrice['savePercent'].'</td>';
}
$_qtyRow .= '</tr>';
$_priceRow .= '</tr>';
$_saveRow .= '</tr>';
echo $_qtyRow;
echo $_priceRow;
echo $_saveRow;
?>
<tr><td>Footer</td></tr>
</table>
I hope this will help.
I don't know what you have in $_tierPrices so i am giving you an example by for some other data.
$arr = array('4','12','20','40'); //suppose you have array like this
$end = end($arr); //We need to find last element of the array to show like 40+
for($i=0;$i<count($arr);$i++){
if($arr[$i] != $end){
echo $arr[$i]."-".($arr[$i+1]-1)." | ";
} else{
echo $arr[$i]."+";
}
}
Output will be like
4-11 | 12-19 | 20-39 | 40+
<?php
echo "<table><tr>";//opening the table
$first_iteration = FALSE;
foreach ($_tierPrices as $value)
{
if (!$first_iteration)//code that only runs on the first iteration
{
$first_iteration = TRUE;
$buffer_value = $value;
}
else {//code that runs after the first iteration
$buff = ((integer)$value)-1;//calculation1 value previous
$output = $buffer_value."-".$buff;
echo "<td>".$output."</td>";
$buffer_value = $value;
}
}
echo "<td>".$buffer_value."+</td>";
echo "</tr></table>";//closing the table
?>
let me know if that worked for you :)
Related
I am looking to group an array into subarrays based on its keys.
Sample Array
Array
(
[0] => Array
(
[a_id] => 1
[a_name] => A1
[b_id] => 1
[b_name] => B1
[c_id] => 1
[c_name] => C1
)
[1] => Array
(
[a_id] => 1
[a_name] => A1
[b_id] => 1
[b_name] => B1
[c_id] => 2
[c_name] => C2
)
[2] => Array
(
[a_id] => 1
[a_name] => A1
[b_id] => 2
[b_name] => B2
[c_id] => 3
[c_name] => C3
)
[3] => Array
(
[a_id] => 2
[a_name] => A2
[b_id] => 3
[b_name] => B3
[c_id] => 4
[c_name] => C4
)
)
I need this sample array to be converted into a JSON array of the following format:
Expected Output
[{
"a_id": 1,
"a_name": "A1",
"b_list": [{
"b_id": 1,
"b_name": "B1",
"c_list": [{
"c_id": 1,
"c_name": "C1"
}, {
"c_id": 2,
"c_name": "C2"
}]
}, {
"b_id": 2,
"b_name": "B2",
"c_list": [{
"c_id": 3,
"c_name": "C3"
}]
}]
}, {
"a_id": 2,
"a_name": "A2",
"b_list": [{
"b_id": 3,
"b_name": "B3",
"c_list": [{
"c_id": 4,
"c_name": "C4"
}]
}]
}]
I was able to group by a key using the code below.
$array = array(
array("a_id" => "1","a_name" => "A1","b_id" => "1","b_name" => "B1","c_id" => "1","c_name" => "C1"),
array("a_id" => "1","a_name" => "A1","b_id" => "1","b_name" => "B1","c_id" => "2","c_name" => "C2"),
array("a_id" => "1","a_name" => "A1","b_id" => "2","b_name" => "B2","c_id" => "3","c_name" => "C3"),
array("a_id" => "2","a_name" => "A2","b_id" => "3","b_name" => "B3","c_id" => "4","c_name" => "C4")
);
$return = array();
foreach($array as $val) {
$return[$val["a_id"]][] = $val;
}
print_r($return);
But my actual scenario involves grouping into sub arrays didn't worked.
Looking forward to see if there is an optimized way or useful function to get into my expected JSON response.
Note: I am looking into a generalized use case here . For example : a_list as countries,b_list as states and c_list as cities.
Man that is very specific use case for arrays. Well here is your solution.
$array = <YOUR SAMPLE ARRAY>
$output = [];
/*
* Nesting array based on a_id, b_id
*/
foreach ($array as $item) {
$aid = $item['a_id'];
$bid = $item['b_id'];
$cid = $item['c_id'];
if(!isset($output[$aid])){
$output[$aid] = [
'a_id' => $item['a_id'],
'a_name' => $item['a_name'],
'b_list' => [
$bid => [
'b_id' => $item['b_id'],
'b_name' => $item['b_name'],
'c_list' => [
$cid = [
'c_id' => $item['c_id'],
'c_name' => $item['c_name']
]
]
]
]
];
} else if (!isset($output[$aid]['b_list'][$bid])){
$output[$aid]['b_list'][$bid] = [
'b_id' => $item['b_id'],
'b_name' => $item['b_name'],
'c_list' => [
$cid => [
'c_id' => $item['c_id'],
'c_name' => $item['c_name']
]
]
];
} else if(!isset($output[$aid]['b_list'][$bid]['c_list'][$cid])) {
$output[$aid]['b_list'][$bid]['c_list'][$cid] = [
'c_id' => $item['c_id'],
'c_name' => $item['c_name']
];
} else {
// Do/Dont overrider
}
}
/*
* Removing the associativity from the b_list and c_list
*/
function indexed($input){
$output = [];
foreach ($input as $key => $item) {
if(is_array($item)){
if($key == 'b_list' || $key == 'c_list'){
$output[$key] = indexed($item);
} else {
$output[] = indexed($item);
}
} else {
$output[$key] = $item;
}
}
return $output;
}
$indexed = indexed($output);
print_r(json_encode($indexed, 128));
Interesting requirement there.
Here is my generalized solution that is also extendable.
function transform($array, $group=[
['a_id','a_name','b_list'],
['b_id','b_name','c_list'],
['c_id','c_name'],
]){
foreach($array as $a){
$r = &$result;
foreach($group as $g){
$x = &$r[$a[$g[0]]];
$x[$g[0]] = $a[$g[0]];
$x[$g[1]] = $a[$g[1]];
if(isset($g[2])) $r = &$x[$g[2]]; else break;
}
}
return transformResult($result);
}
function transformResult($result){
foreach($result as &$a)
foreach($a as &$b)
if(is_array($b)) $b = transformResult($b);
return array_values($result);
}
To extend this solution, all you have to do is modify the $group parameter,
either directly in the function declaration or by passing an appropriate value as the 2nd parameter.
Usage example:
echo json_encode(transform($array), JSON_PRETTY_PRINT);
This will return the same output assuming the same $array input in your example.
Now here is the code that works best in the given situation. I have created a similar situation and then explained the solution in detail.
Situation
The Order Form is multipage depending on the number of days served based on the package selected. Details of each package are stored in the database with the following fields:
package_id (Unique Field)
package_name (Name of the Package, e.g. Package A)
servings_count (Total Servings in a Day)
days_served (Number of Days Served in a Month)
In order to carry forward the selection of meals for each day and serving of that day to store as an Order in the database, I required a Multidimensional Array of PHP that can be defined/populated dynamically.
Expected output is something like:
Array
(
[Day 1] => Array
(
[meal_id_1] => Unique ID //to be replaced with user selection
[meal_code_1] => Meal Name //to be replaced with user selection
[meal_type_1] => Meal //prefilled based on the selected package
[meal_id_2] => Not Available //to be replaced with user selection
[meal_code_2] => 2 //to be replaced with user selection
[meal_type_2] => Meal //prefilled based on the selected package
)
[Day 2] => Array
(
[meal_id_1] => Unique ID //to be replaced with user selection
[meal_code_1] => Meal Name //to be replaced with user selection
[meal_type_1] => Meal //prefilled based on the selected package
[meal_id_2] => Not Available //to be replaced with user selection
[meal_code_2] => 2 //to be replaced with user selection
[meal_type_2] => Meal //prefilled based on the selected package
)
This above array has been created 100% dynamically based on the explained structure and number of servings and days. Below is the code with some explanation.
First, we have to declare two PHP Arrays.
$total_meals_array = []; //Primary, Multidimension Array
$meals_selected_array = []; //Meals Details Array to be used as primary array's key value.
After doing this, run MySQL query to read packages from the database. Now based on the result, do the following:
$total_meals_array = []; //Primary, Multidimension Array
$meals_selected_array = []; //Meals Details Array to be used as primary array's key value.
if( $num_row_packages >= 1 ) {
while($row_packages = mysqli_fetch_array ($result_packages)) {
$package_id = $row_packages['package_id'];
$package_name = $row_packages['package_name'];
$servings_count = $row_packages['servings_count'];
$days_served = $row_packages['days_served'];
//this for loop is to repeat the code inside `$days_served` number of times. This will be defining our primary and main Multidimensional Array `$total_meals_array`.
for ($y = 1; $y <= $days_served; $y++) {
//once inside the code, now is the time to define/populate our secondary array that will be used as primary array's key value. `$i`, which is the meal count of each day, will be added to the key name to make it easier to read it later. This will be repeated `$meals_count` times.
for ($i = 1; $i <= $meals_count; $i++) {
$meals_selected_array["meal_id_" . $i] = "Unique ID";
$meals_selected_array["meal_code_" . $i] = "Meal Name";
$meals_selected_array["meal_type_" . $i] = "Meal";
}
//once our secondary array, which will be used as the primary array's key value, is ready, we will start defining/populating our Primary Multidimensional Array with Keys Named based on `$days_served`.
$total_meals_array["Day " . $y] = $meals_selected_array;
}
}
}
That's it! Our dynamic Multidimensional Array is ready and can be viewed by simply the below code:
print "<pre>";
print_r($total_meals_array);
print "</pre>";
Thank you everyone, specially #yarwest for being kind enough to answer my question.
Here is the code, you can use it for index from a_ to y_ deep. The innerest element is null, if you don't want it. Terminate the for loop before last element, then process last element seperately. You also can do some improvement on this code. Hope this helps.
<?php
$array = array(
array("a_id" => "1","a_name" => "A1","b_id" => "1","b_name" => "B1","c_id" => "1","c_name" => "C1"),
array("a_id" => "1","a_name" => "A1","b_id" => "1","b_name" => "B1","c_id" => "2","c_name" => "C2"),
array("a_id" => "1","a_name" => "A1","b_id" => "2","b_name" => "B2","c_id" => "3","c_name" => "C3"),
array("a_id" => "2","a_name" => "A2","b_id" => "3","b_name" => "B3","c_id" => "4","c_name" => "C4")
);
$arrays = array_map(function($v){return array_chunk($v, 2, true);}, $array);
$result = [];
foreach($arrays as $value)
{
$ref = &$result;
$len = count($value);
$index = 0;
for(; $index < $len; $index++)
{
$arr = $value[$index];
$char = key($arr)[0];
$charAdd = chr(ord($char)+1);
$key = $arr[$char.'_id'].$arr[$char.'_name'];
$listKey = $charAdd.'_list';
foreach($arr as $k => $v)
{
$ref[$key][$k] = $v;
}
$ref = &$ref[$key][$listKey];
}
}
var_dump($result);
Output: the online live demo
ei#localhost:~$ php test.php
array(2) {
["1A1"]=>
array(3) {
["a_id"]=>
string(1) "1"
["a_name"]=>
string(2) "A1"
["b_list"]=>
array(2) {
["1B1"]=>
array(3) {
["b_id"]=>
string(1) "1"
["b_name"]=>
string(2) "B1"
["c_list"]=>
array(2) {
["1C1"]=>
array(3) {
["c_id"]=>
string(1) "1"
["c_name"]=>
string(2) "C1"
["d_list"]=>
NULL
}
["2C2"]=>
array(3) {
["c_id"]=>
string(1) "2"
["c_name"]=>
string(2) "C2"
["d_list"]=>
NULL
}
}
}
["2B2"]=>
array(3) {
["b_id"]=>
string(1) "2"
["b_name"]=>
string(2) "B2"
["c_list"]=>
array(1) {
["3C3"]=>
array(3) {
["c_id"]=>
string(1) "3"
["c_name"]=>
string(2) "C3"
["d_list"]=>
NULL
}
}
}
}
}
["2A2"]=>
array(3) {
["a_id"]=>
string(1) "2"
["a_name"]=>
string(2) "A2"
["b_list"]=>
array(1) {
["3B3"]=>
array(3) {
["b_id"]=>
string(1) "3"
["b_name"]=>
string(2) "B3"
["c_list"]=>
array(1) {
["4C4"]=>
array(3) {
["c_id"]=>
string(1) "4"
["c_name"]=>
string(2) "C4"
["d_list"]=>
&NULL
}
}
}
}
}
}
This is rather interesting. As far as I can tell, you are trying to transform a flat array into a multidimensional array, as well as transforming the keys into a multidimensional representation.
The top level difference seems to reside in the part before the underscore of the a_* keys.
Then, for each of these keys, every other *_ letters should induce it's own list.
This recursive function does the trick without hardcoding, will work with whatever number of levels, letters (or whatever else) and right identifiers.
It seems to return exactly the json you show in the sample ($array being the array as defined in your question)
$multidimension = multidimensionalify($array, ['a', 'b', 'c'], ['name']);
var_dump(json_encode($multidimension, JSON_PRETTY_PRINT));
function multidimensionalify(
array $input,
array $topLevelLetters,
array $rightHandIdentifiers,
$level = 0,
$parentId = null,
$uniqueString = 'id'
)
{
$thisDimension = [];
$thisLetter = $topLevelLetters[$level];
foreach ($input as $entry)
{
$thisId = $entry["{$thisLetter}_{$uniqueString}"];
$condition = true;
if ($parentId !== null)
{
$parentLetter = $topLevelLetters[$level - 1];
$condition = $entry["{$parentLetter}_{$uniqueString}"] === $parentId;
}
if (!isset($thisDimension[$thisId]) && $condition)
{
$thisObject = new stdClass;
$thisObject->{"{$thisLetter}_{$uniqueString}"} = $thisId;
foreach ($rightHandIdentifiers as $identifier)
{
$thisObject->{"{$thisLetter}_{$identifier}"} = $entry["{$thisLetter}_{$identifier}"];
}
if (isset($topLevelLetters[$level + 1])) {
$nextLetter = $topLevelLetters[$level + 1];
$thisObject->{"{$nextLetter}_list"} = multidimensionalify($input, $topLevelLetters, $rightHandIdentifiers, $level + 1, $thisId, $uniqueString);
}
$thisDimension[$thisId] = $thisObject;
}
}
return array_values($thisDimension);
}
Try this function just pass your array and key name for grouping and then convert to json.
public function _group_by($array, $key) {
$return = array();
foreach ($array as $val) {
$return[$val[$key]][] = $val;
}
return $return;
}
I want to compare the values of sandra_array with john_array and then with sem_array.
I can compare sandra_array with john_array with:
<?php
$sandra_array = array("soccer" => "10", "basketball" => "20", "atletics" => "40");
$john_array = array("soccer" => "15", "basketball" => "15", "atletics" => "45");
$sem_array = array("soccer" => "5", "basketball" => "10", "atletics" => "50");
$common_sports = array_keys(array_intersect_key($sandra_array, $john_array));
$points_sandra_array = $points_john_array = array_fill_keys($common_sports, 0);
foreach ($common_sports as $common_sport) {
if ($sandra_array[$common_sport] > $john_array[$common_sport]) {
$points_sandra_array[$common_sport]++;
} else if ($sandra_array[$common_sport] < $john_array[$common_sport]) {
$points_john_array[$common_sport]++;
}
}
foreach ($common_sports as $common_sport) {
}
echo "Sandra (", array_sum($points_sandra_array).") vs John (", array_sum($points_john_array).")";
?>
Result
Sandra (1) vs John (2)
I want to have also the results of Sandra against Sem. Like this:
Sandra (1) vs John (2)
Sandra (2) vs Sem(1)
I was thinking about making the following multidimensional array:
$array_other_players = array($john_array,$sem_array);
and then with foreach I will compare first the points of Sandra with the points of John and then with the points of Sem. But I don't know how to do it.
Could you help me with this?
The solution is:
First declare an array containing opponents players' array, like this:
$players_array = array('John' => $john_array, 'Sem' => $sem_array);
And then loop through each opponent player to calculate the final score.
So your code should be like this:
$sandra_array = array("soccer" => "10", "basketball" => "20", "atletics" => "40");
$john_array = array("soccer" => "15", "basketball" => "15", "atletics" => "45");
$sem_array = array("soccer" => "5", "basketball" => "10", "atletics" => "50");
// Declare an array containing opponents players' array
$players_array = array('John' => $john_array, 'Sem' => $sem_array);
// Loop through each opponent player to calculate the final score
foreach($players_array as $opponent_player => $opponent_player_array){
$common_sports = array_keys(array_intersect_key($sandra_array, $opponent_player_array));
$points_sandra_array = $points_opponent_array = array_fill_keys($common_sports, 0);
foreach ($common_sports as $common_sport) {
if ($sandra_array[$common_sport] > $opponent_player_array[$common_sport]) {
$points_sandra_array[$common_sport]++;
} else if ($sandra_array[$common_sport] < $opponent_player_array[$common_sport]) {
$points_opponent_array[$common_sport]++;
}
}
echo "Sandra (". array_sum($points_sandra_array).") vs {$opponent_player} (". array_sum($points_opponent_array) .")<br />";
}
Output:
Sandra (1) vs John (2)
Sandra (2) vs Sem (1)
I have the below code in a for..loop is there a way I can add values to the beginning of the array?
$data = array();
$initial = strtotime('11:00:00');
for (; $initial < strtotime("23:00:59"); $initial = strtotime("+15 minutes", $initial)) {
if ($initial > strtotime("+45 minutes", time())) {
$row['value'] = date('Hi', $initial);
$row['label'] = date('H:i', $initial);
$data['data'][] = $row;
}
}
I want to add the below values to the top of the array. I have tried using array_unshift but I don't think it supports key-value pairs.
if(!isBetween('22:00', '09:59', date('H:i'))) {
$row['value'] = "asap";
$row['label'] = "ASAP";
}
My array output
{
"data": [
{
"value": "1145",
"label": "11:45"
}
]
}
I want to get this
{
"data": [
{
"value": "asap",
"label": "ASAP"
},{
"value": "1145",
"label": "11:45"
},
]
}
Un-shift should work if you pass the arguments correctly:
array_unshift($data["data"], $prepend);
Alternatively, you could use array_merge, like this:
$data["data"] = array_merge(array($prepend), $data["data"]);
With the following example data:
$data = [
"data" => [
[
"value" => "1145",
"label" => "11:45"
]
]
];
$prepend = [
"value" => "asap",
"label" => "ASAP"
];
$data["data"] = array_merge(array($prepend), $data["data"]);
print_r($data);
You would get this output (with both solutions):
Array (
[data] => Array (
[0] => Array (
[value] => asap
[label] => ASAP
)
[1] => Array (
[value] => 1145
[label] => 11:45
)
)
)
If you need to prepend something to the array without the keys being reindexed and/or need to prepend a key value pair, you can use this short function:
function array_unshift_assoc(&$arr, $key, $val) {
$arr = array_reverse($arr, true);
$arr[$key] = $val;
return array_reverse($arr, true);
}
Source: http://php.net/manual/en/function.array-unshift.php
I have a JSON file that contain this:
"Menus": [{
"MenuId": "1",
"MenuName": "Perencanaan dan Pengadaan",
"MenuParent": "",
"MenuLink": ""
}, {
"MenuId": "1-1",
"MenuName": "RKA / DPA",
"MenuParent": "1",
"MenuLink": ""
}, {
"MenuId": "1-1-1",
"MenuName": "Daftar RKA / DPA",
"MenuParent": "1-1",
"MenuLink": "rkbu"
},
I want to put that data into unordered list dynamically. So the output I want is like this (with 3 level list):
Perencanaan dan Pengadaan
RKA / DPA
Daftar RKA / DPA
I have tried this code:
echo "<ul>";
foreach($get_data['Menus'] as $node){
if(strlen($node['MenuId']) == 1){
echo "<li>" . $node['MenuName'];
echo "</li>";
}
echo "<ul>";
if(strlen($node['MenuId']) == 3){
echo "<li>".$node['MenuName']."</li>";
}
if(strlen($node['MenuId']) == 5){
echo "<ul>";
echo "<li>".$node['MenuName']."</li>";
echo "</ul>";
}
echo "</ul>";
}
echo "</ul>";
But I find that it is not dynamic because it depends on string length. I've read that the best method is using recursive method. But I cannot find the recursive pattern of my JSON file. Can anybody help me find the solution? Thanks
I don't think it is possible to make recursive calls directly on your flat JSON data.
I suggest you first convert your flat data to a multidimensional array and afterwards recursively generate your menu.
I took parts of the code from here: Dynamically creating/inserting into an associative array in PHP
$get_data = array(
array(
"MenuId" => "1",
"MenuName" => "Perencanaan dan Pengadaan",
"MenuParent" => "",
"MenuLink" => ""
),
array(
"MenuId" => "1-1",
"MenuName" => "RKA / DPA",
"MenuParent" => "1",
"MenuLink" => ""
),
array(
"MenuId" => "1-1-1",
"MenuName" => "Daftar RKA / DPA",
"MenuParent" => "1-1",
"MenuLink" => "rkbu"
)
);
function insert_into(&$array, array $keys, $value) {
$last = array_pop($keys);
foreach($keys as $key) {
if(!array_key_exists($key, $array) ||
array_key_exists($key, $array) && !is_array($array[$key])) {
$array[$key]['items'] = array();
}
$array = &$array[$key]['items'];
}
$array[$last]['value'] = $value;
}
function create_menu($menuItems) {
$content = '<ul>';
foreach($menuItems as $item) {
$content .= '<li>' . $item['value'];
if(isset($item['items']) && count($item['items'])) {
$content .= create_menu($item['items']);
}
$content .= '</li>';
}
$content .= '</ul>';
return $content;
}
$menuItems = array();
foreach($get_data as $item) {
$levels = explode('-', $item['MenuId']);
insert_into($menuItems, $levels, $item['MenuName']);
}
print_r($menuItems);
print create_menu($menuItems);
DEMO: http://3v4l.org/dRK4f
Output:
Array (
[1] => Array (
[value] => Perencanaan dan Pengadaan
[items] => Array (
[1] => Array (
[value] => RKA / DPA
[items] => Array (
[1] => Array (
[value] => Daftar RKA / DPA
)
)
)
)
)
)
<ul>
<li>Perencanaan dan Pengadaan
<ul>
<li>RKA / DPA
<ul>
<li>Daftar RKA / DPA</li>
</ul>
</li>
</ul>
</li>
</ul>
I'm sure there's a fairly easy way to do this. I have an the following data in an array:
Array
(
[ActivityDiaryEntry] => Array
(
[date] => 2011-03-03
[type] => Walking
[minutes] => 60
)
)
Array
(
[ActivityDiaryEntry] => Array
(
[date] => 2011-03-02
[type] => Walking
[minutes] => 22
)
)
Array
(
[ActivityDiaryEntry] => Array
(
[date] => 2011-03-01
[type] => Biking
[minutes] => 45
)
)
I'm not too skilled at PHP, but I know how to display this data by row to display as <tr><td>[date]</td><td>[type]</td><td>[minutes]</td></tr>. But I'd like to have the data display in columns like this:
2011-03-01 | 2011-03-02 | 2011-03-03
------------------------------------
Biking | Walking | Walking
------------------------------------
45 | 22 | 60
I didn't test this, but it should work. It should serve as an example of what needs to be done. I tried to write this to limit the number of foreach loops used. If I reordered the data first and then performed the takes, I'd of needed 4 foreach loops. The benefit to this method is that you don't need to update the code if more columns are added, so long as all records have the same number of columns.
<?php
// Your list of records
$records = array(
array( "key1" => "value", "key2" => "value", "key3" => "value" ),
array( "key1" => "value", "key2" => "value", "key3" => "value" ),
array( "key1" => "value", "key2" => "value", "key3" => "value" )
);
// Create an array to store the values of each row based on number of columns in first value
$rows = array_fill( 0, count( $records[0] ), "" );
$keys = array_keys( $records[0] );
// Create a column for each record in it's respective row.
foreach( $records as $k => $record )
for( $i=0, $max=count( $rows ); $i < $max; $i++ )
$rows[ $i ] .= "<td>".$record[ $keys[ $i ] ]."</td>";
// Turn each row in our array into an html table row.
print "<tr>".implode( "</tr><tr>", $rows )."</tr>";
Here's the code test: http://codepad.org/SSS8S2eU
A little ugly but works :')
$a[0] = array('ActivityDiaryEntry' => array("date" => "2011-03-03", "type"=> "Walking", "minutes" => 60));
$a[1] = array('ActivityDiaryEntry' => array("date" => "2011-03-03", "type"=> "Walking", "minutes" => 22));
$a[2] = array('ActivityDiaryEntry' => array("date" => "2011-03-03", "type"=> "Biking", "minutes" => 42));
$keys = array_keys($a[0]["ActivityDiaryEntry"]);
echo '<table>';
for($c = 0; $c < count($a); $c++) {
echo '<tr>';
for($i = 0; $i < count($a[$c]['ActivityDiaryEntry']); $i++) {
echo '<td>' . $a[$i]['ActivityDiaryEntry'][$keys[$c]] . '</td>';
}
echo '</tr>';
}
echo '</table>';
http://codepad.org/5Tuk8x3Q
This code works if i am not wrong defining the array, but i suggest you play with all the options provided here and find a better solution.
$data = array (
array (
'ActivityDiaryEntry' => array
(
'date' => "2011-03-03",
'type' => "Walking",
'minutes' => 60
)
),
array (
'ActivityDiaryEntry' => array
(
'date' => "2011-03-02",
'type' => Walking,
'minutes' => 22
) ),
array (
'ActivityDiaryEntry' => array
(
'date' => "2011-03-01",
'type' => Biking,
'minutes' => 45
)
)
);
echo "<table>";
$i = 0;
foreach ($data as $key => $val) {
echo "<tr>";
foreach ($data as $kk => $vv){
if ($i==0) {
echo "<td>". $vv['ActivityDiaryEntry']['date'] ."</td>";
}else if ($i == 1){
echo "<td>". $vv['ActivityDiaryEntry']['type'] ."</td>";
}else if ($i == 2){
echo "<td>". $vv['ActivityDiaryEntry']['minutes'] ."</td>";
}
}
echo "</tr>";
$i++;
}
echo "</table>";
This would be a great candidate for DataTables, which is actually Javascript that I use to display my results generated on the back end by PHP. It's a full-blown javascript grid system that adds a ton of features to standard HTML table outputs. To make it work you would:
Get your results as shown and output as a json_encoded string (i.e, echo json_encode($array) I do this in a separate file so it outputs clean text to the screen.
On the page to display the table, setup a "dummy table"
Setup Datatables in the same page as the dummy table like this:
$(document).ready(function() {
$('#replace').dataTable( {
"bProcessing": true,
"sAjaxSource": 'file.php'
} );
} );
Set values for sorting, filtering, paging, etc. per the tutorial.
Datatables gives you so much more power than just a standard HTML table, and you're already 90% of the way there with the data. It's so much more user friendly than just jamming stuff on the screen.
Before transposing your data (converting columns to rows), you must reduce the depth/complexity by removing the unusable first level and generate an indexed array of what is left.
Then iterate the first array in the new, simplified data structure and extract column data. Each column (there are three) will be displayed in its own table row using a flexible implode()ing technique.
Code: (Demo)
$subarrays = array_column($array, "ActivityDiaryEntry");
echo '<table>';
foreach ($subarrays[0] as $column => $notUsed) {
echo '<tr><td>' , implode('</td><td>', array_column($subarrays, $column)) , '</td></tr>';
}
echo '</table>';
Output:
<table>
<tr>
<td>2011-03-03</td>
<td>2011-03-03</td>
<td>2011-03-03</td>
</tr>
<tr>
<td>Walking</td>
<td>Walking</td>
<td>Biking</td>
</tr>
<tr>
<td>60</td>
<td>22</td>
<td>42</td>
</tr>
</table>
You could write a for loop for each field, displaying one row in each loop.
The Javascript answer below might be a good way to do it, but I would suggest using PHP and tables if you are not completely comfortable using Javascript in your applications. It is also good PHP practice.
If I were you, I'd use code like this, and css properties to format the table how you'd like.
echo '<table>';
echo '<tr><td>Date</td><td>Type</td><td>Minutes</td></tr>';
foreach ($array as $entry){
echo '<tr>';
echo '<td>'.$entry['date'].'</td>';
echo '<td>'.$entry['type'].'</td>';
echo '<td>'.$entry['minutes'].'</td>';
echo '</tr>';
}
echo '</table>';
You can use stuff like this to edit your tables display, also check out http://www.w3schools.com/css/css_table.asp
echo '<tr style="border-bottom: 1px solid black;"></tr>';
cheers