PHP Sum Children in Array - php

Hey I have an array where I would like to sum the values of the first-level children at various levels of the array.
<?php
$group = Array('Electronics' => Array(
'6 - Cameras & Supplies' => Array(
'Cameras' => Array(
'Camcorders' => Array (
'Action Camcorders' => Array (
'total_ty_yest_sales' => 70.83,
'total_wo_dotcom_ty_yest_sales' => 401.59,
'east_ty_yest_sales' => 65.20
),
'Standard Camcorders' => Array (
'total_ty_yest_sales' => 96.09,
'total_wo_dotcom_ty_yest_sales' => 96.09,
'east_ty_yest_sales' => 68.21
),
'Surveillance' => Array(
'total_ty_yest_sales' => 84.00,
'total_wo_dotcom_ty_yest_sales' => 84.00,
'east_ty_yest_sales' => 26.00
)
),
'subCameras' => Array (
'Big Zoom' => Array(
'total_ty_yest_sales' => 31.66,
'total_wo_dotcom_ty_yest_sales' => 13.68,
'east_ty_yest_sales' => 1.47
),
'Pegged Cameras' => Array(
'total_ty_yest_sales' => 13.50,
'total_wo_dotcom_ty_yest_sales' => 5.50,
'east_ty_yest_sales' => 5.00
),
'Point-N-Shoot' => Array(
'total_ty_yest_sales' => 46.61,
'total_wo_dotcom_ty_yest_sales' => 10.35,
'east_ty_yest_sales' => 4.06
),
'Rugged Cameras' => Array(
'total_ty_yest_sales' => 87.04,
'total_wo_dotcom_ty_yest_sales' => 87.04,
'east_ty_yest_sales' => 65.20
),
'SLR' => Array(
'total_ty_yest_sales' => 50.19,
'total_wo_dotcom_ty_yest_sales' => 9.40,
'east_ty_yest_sales' => 1.37
)
)
) )
));
$totalSum = 0;
echo "<table>\n
<thead></thead>\n
<tbody>\n";
foreach($group as $gmm => $acctg_dept_nbrs) {
echo "<tr class=\"header\">\n
<td>" . $gmm . "</td>\n";
foreach ($acctg_dept_nbrs as $acctg_dept_nbr => $dept_catg_grp_descs) {
echo "<tr class=\"header\">\n
<td style=\"padding-left: 1em;\">" . $acctg_dept_nbr . "</td>\n";
echo "<td style=\"width:100px;\">SUM</td>\n";
echo "<td style=\"width:100px;\">SUM</td>\n";
echo "<td style=\"width:100px;\">SUM</td>\n";
$total_acctg_dept_nbr = 0;
foreach($dept_catg_grp_descs as $dept_catg_grp_desc => $dept_category_descs) {
echo "<tr class=\"header\">\n
<td style=\"padding-left: 2em;\">" . $dept_catg_grp_desc . "</td>\n";
echo "<td style=\"width:100px;\">SUM</td>\n";
echo "<td style=\"width:100px;\">SUM</td>\n";
echo "<td style=\"width:100px;\">SUM</td>\n";
$total_dept_catg_grp_desc = 0;
foreach($dept_category_descs as $dept_category_desc => $dept_subcatg_descs) {
echo "<tr class=\"header\">\n
<td style=\"padding-left: 3em;\">" . $dept_category_desc . "</td>\n";
echo "<td style=\"width:100px;\">SUM</td>\n";
echo "<td style=\"width:100px;\">SUM</td>\n";
echo "<td style=\"width:100px;\">SUM</td>\n";
foreach($dept_subcatg_descs as $dept_subcatg_desc => $values) {
echo "<tr>\n
<td style=\"padding-left: 4em;\">" . $dept_subcatg_desc . "</td>\n";
$sum = $values['total_ty_yest_sales'];
echo "<td style=\"width:100px;\">".$sum."</td>\n";
$sum = $values['total_wo_dotcom_ty_yest_sales'];
echo "<td style=\"width:100px;\">".$sum."</td>\n";
$sum = $values['east_ty_yest_sales'];
echo "<td style=\"width:100px;\">".$sum."</td>\n";
}
}
}
}
}
?>
I want to replace the "SUM"s in the output with the sum of the values of next level of indention.

This is not the most efficient thing to do, but you can create a function that calculates the sum of an array recursively:
function array_sum_recursive($array)
{
$sum = 0;
array_walk_recursive($array, function($item) use (&$sum) {
$sum += $item;
});
return $sum;
}

Related

Multi-dimensional PHP array of values not displaying correctly

I have a multidimensional array of fruits below.
$fruits = [
'ORANGE' =>
[
'Size' => '0.20',
'Cost' => '0.49',
'Lbs.' => '0.60',
]
'LEMON' =>
[
'Size' => '0.15',
'Cost' => '0.29',
'Lbs.' => '0.20',
]
];
I want to display the fruit array like below, but it is not working as expected.
-----| ORANGE | LEMON |
Size | 0.20 | 0.15 |
Cost | 0.49 | 0.29 |
Lbs. | 0.60 | 0.20 |
My code below is not quite doing what I expected. Any suggestions? Thank you!
echo '<table id="fruits" style="width:400px;border:1px solid black;">' . PHP_EOL;
echo '<tbody>' . PHP_EOL;
foreach ($fruits as $fruitkey => $fruitvalue) {
echo '<th>' . $fruitkey . '</th>';
foreach ($fruitvalue as $key => $value) {
echo '<tr>' . PHP_EOL;
echo '<td>' . PHP_EOL;
echo $key . PHP_EOL;
echo '</td>' . PHP_EOL;
echo '<td>' . PHP_EOL;;
echo number_format($value, 2) . PHP_EOL;
echo '</td>' . PHP_EOL;
echo '</tr>' . PHP_EOL;
}
}
echo '</tbody>' . PHP_EOL;
echo '</table">' . PHP_EOL;
Can you try the below code
<?php
$fruits = [
'ORANGE' =>
[
'Size' => '0.20',
'Cost' => '0.49',
'Lbs.' => '0.60',
],
'LEMON' =>
[
'Size' => '0.15',
'Cost' => '0.29',
'Lbs.' => '0.20',
]
];
$keys = array_keys($fruits);
if(!empty($keys))
$innerKeys = array_keys($fruits[$keys[0]]);
echo '<table id="fruits" style="width:400px;border:1px solid black;">';
echo '<thead><tr>';
echo '<td>----</td>';
foreach($keys as $key)
echo '<td>'.$key.'</td>';
echo '</tr></thead>';
echo '<tbody>';
foreach($innerKeys as $inKey){
echo '<tr>';
echo '<td>'.$inKey.'</td>';
foreach($fruits as $fKey => $val){
echo '<td>'.$val[$inKey].'</td>';
}
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
Demo Link

how to create table using multiple dimensional array in php

Actually This are my real data from API.
$main2 = array(
'sup1' => array(
'01-Jun-2019-TO-03-Jun-2019' => array("connection_count" => 54, "source_type" => 'TATA'),
'04-Jun-2019-TO-08-Jun-2019' => array("connection_count" => 10, "source_type" => 'Rel'),
),
'sup2' => array(
'01-Jun-2019-TO-03-Jun-2019' => array("connection_count" => 54, "source_type" => 'TCS'),
'04-Jun-2019-TO-08-Jun-2019' => array("connection_count" => 55, "source_type" => 'Jio'),
),
);
We need same out put using this array.
we create table all date in header like first key date as display in header.
-then data display supplier sup1 in first row
sup2 in second row row
like below out put
|Supplier Name |01-Jun-2019-TO-03-Jun-2019 |04-Jun-2019-TO-08-Jun-2019|<br/>
|sup1|54|TATA|10|Rel|
<br/>
|sup2|54|TCS|55|JIO|
Here is your code modified:
<?php
$main2 = array(
'01-Jun-2019-TO-03-Jun-2019' => array(
'sup1' => array("connection_count" => 54, "source_type" => 'TATA'),
'sup2' => array("connection_count" => 10, "source_type" => 'Rel'),
),
'04-Jun-2019-TO-08-Jun-2019' => array(
'sup1' => array("connection_count" => 54, "source_type" => 'TCS'),
'sup2' => array("connection_count" => 55, "source_type" => 'Jio'),
),
);
$suplist = array('sup1', 'sup2');
echo "<table border=1><tr>";
echo "<td>Supplier Name</td>";
foreach ($main2 as $key => $value) {
echo "<td colspan=2>" . $key . "</td>";
}
echo "</tr>";
foreach ($suplist as $supplier) {
echo "<tr><td>$supplier</td>";
foreach ($main2 as $value) {
echo "<td>" . $value[$supplier]['connection_count'] . "</td>";
echo "<td>" . $value[$supplier]['source_type'] . "</td>";
}
echo "</tr>";
}
echo "</table>";
And here is sample output (reformatted for clarity):
<table border=1>
<tr>
<td>Supplier Name</td>
<td colspan=2>01-Jun-2019-TO-03-Jun-2019</td>
<td colspan=2>04-Jun-2019-TO-08-Jun-2019</td>
</tr>
<tr>
<td>sup1</td>
<td>54</td>
<td>TATA</td>
<td>54</td>
<td>TCS</td>
</tr>
<tr>
<td>sup2</td>
<td>10</td>
<td>Rel</td>
<td>55</td>
<td>Jio</td>
</tr>
</table>
Here is your code which works with updated input data format:
$main2 = array(
'sup1' => array(
'01-Jun-2019-TO-03-Jun-2019' => array("connection_count" => 54, "source_type" => 'TATA'),
'04-Jun-2019-TO-08-Jun-2019' => array("connection_count" => 10, "source_type" => 'Rel'),
),
'sup2' => array(
'01-Jun-2019-TO-03-Jun-2019' => array("connection_count" => 54, "source_type" => 'TCS'),
'04-Jun-2019-TO-08-Jun-2019' => array("connection_count" => 55, "source_type" => 'Jio'),
),
);
$suppliers = array_keys($main2);
$dateRanges = [];
foreach ($main2 as $supplierData) {
$dateRanges = array_merge($dateRanges, array_keys($supplierData));
}
$dateRanges = array_values(array_unique($dateRanges));
sort($dateRanges);
echo "<table border=1><tr>";
echo "<td>Supplier Name</td>";
foreach ($dateRanges as $dateRange) {
echo "<td colspan=2>" . $dateRange . "</td>";
}
echo "</tr>";
foreach ($suppliers as $supplier) {
echo "<tr><td>$supplier</td>";
foreach ($dateRanges as $dateRange) {
if (isset($main2[$supplier][$dateRange])) {
echo "<td>" . $main2[$supplier][$dateRange]['connection_count'] . "</td>";
echo "<td>" . $main2[$supplier][$dateRange]['source_type'] . "</td>";
} else {
echo "<td></td><td></td>";
}
}
echo "</tr>";
}
echo "</table>";
And here is sample output (formatted for clarity):
<table border=1>
<tr>
<td>Supplier Name</td>
<td colspan=2>01-Jun-2019-TO-03-Jun-2019</td>
<td colspan=2>04-Jun-2019-TO-08-Jun-2019</td>
</tr>
<tr>
<td>sup1</td>
<td>54</td>
<td>TATA</td>
<td>10</td>
<td>Rel</td>
</tr>
<tr>
<td>sup2</td>
<td>54</td>
<td>TCS</td>
<td>55</td>
<td>Jio</td>
</tr>
</table>

how to get values using foreach

I am trying to create menu dynamically according to the user input. I have an array like this, I want to get each value by their indices or I want to use the values to create menu by their order:
$menu['main_menu']= array(
'menu_name' =>'main_menu',
'menu_item1'=>array('home' => array('URL' => 'Http://www.google.com','Class name'=>"item_class",'menu_id'=>'new_menu' )),
'menu_item2'=>array('development' => array('URL' => 'Http://www.google.com','Class name'=>"item_class",'sub_menu'=>'0' )),
'menu_item3'=>array('php' => array('URL' => 'Http://www.google.com','Class name'=>"item_class",'sub_menu'=>'development' )),
);
Try the following code:
foreach ($menu['main_menu'] as $item => $menu_item) {
if (is_array($menu_item)) {
foreach ($menu_item as $menu_name => $menu_attr) {
echo "menu name: " . $menu_name;
echo '<br/>';
foreach ($menu_attr as $attr => $val) {
echo $attr . "->" . $val;
echo '<br/>';
}
}
}
else{
echo $item.": ".$menu_item;
echo "<br />";
}
}
$menu['main_menu']= array(
'menu_name' =>'main_menu',
'menu_item1'=>array('home' => array('URL' => 'Http://www.google.com','Class name'=>"item_class",'menu_id'=>'new_menu' )),
'menu_item2'=>array('development' => array('URL' => 'Http://www.google.com','Class name'=>"item_class",'sub_menu'=>'0' )),
'menu_item3'=>array('php' => array('URL' => 'Http://www.google.com','Class name'=>"item_class",'sub_menu'=>'development' )),
'menu_item4'=>array('php2' => array('URL' => 'Http://www.google.com','Class name'=>"item_class",'sub_menu'=>'development' )),
'menu_item5'=>array('development2' => array('URL' => 'Http://www.google.com','Class name'=>"item_class",'sub_menu'=>'0' )),
'menu_item6'=>array('php2' => array('URL' => 'Http://www.google.com','Class name'=>"item_class",'sub_menu'=>'development2' )),
);
$submenus = [];
$mainMenu = [];
$menuStart;
$menuEnd;
//prapring data
foreach($menu['main_menu'] as $item){
if(is_array($item)){
foreach($item as $link){
if(isset($link['sub_menu']) & $link['sub_menu'] != '0'){
$submenus[] = [
'name' => key($item),
'sub_menu' => $link["sub_menu"],
'body' => "<li class='{$link["Class name"]}'><a href='{$link["URL"]}' class='{$link["Class name"]}' id='{$link["menu_id"]}'>" . key($item) . "</a>",
'end' => "</li>"
];
} else {
$mainMenu[] = [
'name' => key($item),
'body' => "<li class='{$link["Class name"]}'><a href='{$link["URL"]}' class='{$link["Class name"]}' id='{$link["menu_id"]}'>" . key($item) . "</a>",
'end' => "</li>"
];
}
}
} else {
$menuStart = "<ul class='{$item}'>";
}
}
/// menu generatig
$menuEnd = '</ul>';
echo $menuStart;
foreach($mainMenu as $menu){
echo $menu['body'];
foreach($submenus as $submenu){
if($submenu["sub_menu"] == $menu['name']){
echo "<ul>";
echo $submenu['body'];
echo "</ul>";
}
}
echo $menu['end'];
}
echo $menuEnd;
Following code may help you.
$menu['main_menu']= array(
'menu_name' =>'main_menu',
'menu_item1'=>array('home' => array('URL' => 'Http://www.google.com','Class name'=>"item_class",'menu_id'=>'new_menu' )),
'menu_item2'=>array('development' => array('URL' => 'Http://www.google.com','Class name'=>"item_class",'sub_menu'=>'0' )),
'menu_item3'=>array('php' => array('URL' => 'Http://www.google.com','Class name'=>"item_class",'sub_menu'=>'development' )),
);
foreach($menu['main_menu'] as $menu_name=>$menu_value){
echo "<br><br>menu_name ". $menu_name;
if(is_array ( $menu_value )){
foreach($menu_value as $k=>$v){
if(is_array ( $v )){
foreach($v as $key=>$value)
echo "<br>key=".$key." value=".$value;
}
}
}
}
truy this
foreach($menu['main_menu'] as $menu_name=>$menu_value)
{
if(is_array($menu_value))
{
foreach($menu_value as $value)
{
if(is_array ( $value ))
{
echo "<a href='{$value["URL"]}' class='{$value["Classname"]}'>" . key($menu_value) . "</a><br />"; //
}
}
}
}

3 dimension Array foreach

Im having some problem displaying a multidimensional array...
$copyscape = array (
'query' => 'www.example.html',
'querywords' => 444,
'count' => 230,
'result' => array(
'number' => array(
'index' => 1,
'url' => 'http://www.archives.gov/exhibits/charters/declaration_transcript.html',
'title' => 'Declaration of Independence - Text Transcript',
'minwordsmatched' => 406,
'viewurl' => 'http://view.copyscape.com/compare/w4med9eso0/1'
)
)
);
Basically I want to display everything and also save it in a variable...
echo "<ul>";
foreach($copyscape as $name => $value)
{
echo "<li>" . $name . " : ". $value . "</li>";
}
echo "</ul>";
I tried inserting another set of foreach inside but it gives me an
Invalid argument supplied for foreach()
Try with this code :
$copyscape = array (
'query' => 'www.example.html',
'querywords' => 444,
'count' => 230,
'result' => array(
'number' => array(
'index' => 1,
'url' => 'http://www.archives.gov/exhibits/charters/declaration_transcript.html',
'title' => 'Declaration of Independence - Text Transcript',
'minwordsmatched' => 406,
'viewurl' => 'http://view.copyscape.com/compare/w4med9eso0/1'
)
)
);
function test_print($item, $key)
{
echo "<li>" . $key . " : ". $item . "</li>";
}
echo "<ul>";
array_walk_recursive($copyscape, 'test_print');
echo "</ul>";
use this
foreach ($copyscape as $key=>$value){
echo "<li>" . $key. " : ". $value. "</li>"; // this for main Array
if (is_array ($value))
{
foreach ($value as $childArrayKey => $childArrayValue ){
echo "<li>" . $childArrayKey . " : ". $childArrayValue . "</li>"; // this for childe array
}
}
}
or
foreach ($copyscape as $key=>$value){
echo "<li>" . $key. " : ". $value. "</li>"; // this for main Array
foreach ($value['result']['number'] as $childArrayKey => $childArrayValue ){
echo "<li>" . $childArrayKey . " : ". $childArrayValue . "</li>"; // this for childe array
}
}
In case if you want to have lists inside of lists (nested levels)..
function outputLevel($arr)
{
echo '<ul>';
foreach($arr as $name => $value)
{
echo '<li>';
if (is_array($value))
outputLevel($value);
else
echo $name . ' : ' . $value;
echo '</li>'
}
echo '</ul>';
}
outputLevel($copyscape);
Try following code:
<?php
$copyscape = array (
'query' => 'www.example.html',
'querywords' => 444,
'count' => 230,
'result' => array(
'number' => array(
'index' => 1,
'url' => 'http://www.archives.gov/exhibits/charters/declaration_transcript.html',
'title' => 'Declaration of Independence - Text Transcript',
'minwordsmatched' => 406,
'viewurl' => 'http://view.copyscape.com/compare/w4med9eso0/1'
)
)
);
MultiDimRecuArray($copyscape);
function MultiDimRecuArray($copyscape) {
echo "<ul>";
foreach ($copyscape as $key=>$val) {
if(is_array($val)){
MultiDimRecuArray($val);
}else{
echo "<li>" . $key . " : ". $val . "</li>";
}
}
echo "</ul>";
}
Try something with a recursive function, like this:
function printArray($array)
{
echo "<ul>";
foreach($array as $name=>$value)
{
if(is_array($value))
{
printArray($value);
}
else
{
echo "<li>" . $name . " : ". $value . "</li>";
}
}
echo "</ul>";
}
$copyscape = array (
'query' => 'www.example.html',
'querywords' => 444,
'count' => 230,
'result' => array(
'number' => array(
'index' => 1,
'url' => 'http://www.archives.gov/exhibits/charters/declaration_transcript.html',
'title' => 'Declaration of Independence - Text Transcript',
'minwordsmatched' => 406,
'viewurl' => 'http://view.copyscape.com/compare/w4med9eso0/1'
)
)
);
printArray($copyscape);
Use this
<?php
$copyscape = array (
'query' => 'www.example.html',
'querywords' => 444,
'count' => 230,
'result' => array(
'number' => array(
'index' => 1,
'url' => 'http://www.archives.gov/exhibits/charters/declaration_transcript.html',
'title' => 'Declaration of Independence - Text Transcript',
'minwordsmatched' => 406,
'viewurl' => 'http://view.copyscape.com/compare/w4med9eso0/1'
)
)
);
PrintMultiDimArray($copyscape);
function PrintMultiDimArray($copyscape) {
echo "<ul>";
foreach ($copyscape as $key=>$val) {
if(is_array($val)){
echo "<li>";
PrintMultiDimArray($val);
echo "</li>";
}else{
echo "<li>" . $key . " : ". $val . "</li>";
}
}
echo "</ul>";
}
?>
try this..
echo '<ul>';
displayList($copyscape);
echo '</ul>';
function displayList($arr)
{
foreach($arr as $name => $value) {
if (is_array($value)) {
displayList($value);
}
else {
echo '<li>';
echo $name . ' : ' . $value;
echo '</li>';
}
}
}
Use this:
function print_stuff($arr){
foreach($arr as $key => $val){
if(is_array($val)){
echo "$key: <ul>";
print_stuff($val);
echo "</ul>";
} else {
echo "<li>$key : $val</li>\n";
}
}
}
echo "<ul>";
print_stuff($copyscape);
echo "</ul>";
The code prints a nested list including the key name of the nested lists:
query : www.example.html
querywords : 444
count : 230
result:
number:
index : 1
url : http://www.archives.gov/exhibits/charters/declaration_transcript.html
title : Declaration of Independence - Text Transcript
minwordsmatched : 406
viewurl : http://view.copyscape.com/compare/w4med9eso0/1

Php muilti array echo

I have a php has below how i can echo in php.
i want to echo like this
Veg.Pizaa =>
Extra = > Cheese, price 50
Vegetables = > Avocado, price 25
The Array Is Below
array
(
'Veg.Pizaa' =>
(
array
(
'Extra' =>
(
array
(
'name' => string '25g Cheese' (length=10),
'price' => string '50' (length=2),
'quanty' => int 13,
'Vegetables' =>
),
array
(
'name' => string 'Avocado' (length=7),
'price' => string '25' (length=2),
'quanty' => int 13,
'Nuts' =>
),
array
(
'name' => string 'Almonds' (length=7),
'price' => string '30' (length=2),
'quanty' => int 21
)
)
)
)
)
I've tried the following code
foreach($sub as $sub) {
var_dump($sub);
echo "<tr>";
echo "<td><h3 style='font-weight: bolder; color: Maroon; line-height: 10px;'>".$sub[0]['productname']
."</h3></td>";
echo "<td><h3 style='font-weight: bolder; color: Maroon; line-height: 10px;'>".$sub[0]['qty']
."</h3></td>";
echo "</tr>";
}
$array = ...;
foreach( $array as $key => $val )
{
echo $key . " =>\n";
foreach( $val as $key2 => $val2 )
{
echo "\t" . $key2 . ' => ' . $val2['name'] . "\n";
}
}
foreach($array as $key => $val)
{
echo $key.' ';
if(is_array($val)
{
foreach($val as $name => $qty)
{
if($name=='name')
{
echo $qty;
}
if($name=='price')
{
echo $name.', '.$qty.'\n<br>';
}
}
}
}
Why don't you just do:
print_r($array)
That's what I'd use to debug an array.

Categories