how to display PHP Multidimensional Arrays? - php

how to display this using foreach in php?
I want to show it as a list.
$quantity=0;
$quantities = array(
array('Jan',($quantity += $ppmpitem->m1)),
array('Feb',($quantity += $ppmpitem->m2)),
array('Mar',($quantity += $ppmpitem->m3)),
array('Apr',($quantity += $ppmpitem->m4)),
array('May',($quantity += $ppmpitem->m5)),
array('Jun',($quantity += $ppmpitem->m6)),
array('Jul',($quantity += $ppmpitem->m7)),
array('Aug',($quantity += $ppmpitem->m8)),
array('Sep',($quantity += $ppmpitem->m9)),
array('Oct',($quantity += $ppmpitem->m10)),
array('Nov',($quantity += $ppmpitem->m11)),
array('Dec',($quantity += $ppmpitem->m12)),
);
return $quantities;

You have several options, so based on your code (and what I added):
<?php
$quantity=0;
// Added this, so we have an object
$array = [
"m1" => 1,
"m2" => 2,
"m3" => 3,
"m4" => 4,
"m5" => 5,
"m6" => 6,
"m7" => 7,
"m8" => 8,
"m9" => 9,
"m10" => 10,
"m11" => 11,
"m12" => 12
];
// Converted array to object
$ppmpitem = json_decode(json_encode($array));
$quantities = array(
array('Jan',($quantity += $ppmpitem->m1)),
array('Feb',($quantity += $ppmpitem->m2)),
array('Mar',($quantity += $ppmpitem->m3)),
array('Apr',($quantity += $ppmpitem->m4)),
array('May',($quantity += $ppmpitem->m5)),
array('Jun',($quantity += $ppmpitem->m6)),
array('Jul',($quantity += $ppmpitem->m7)),
array('Aug',($quantity += $ppmpitem->m8)),
array('Sep',($quantity += $ppmpitem->m9)),
array('Oct',($quantity += $ppmpitem->m10)),
array('Nov',($quantity += $ppmpitem->m11)),
array('Dec',($quantity += $ppmpitem->m12)),
);
// Pretty print
print("<pre>".print_r($quantities,true)."</pre>");
// As a list where Month is key
foreach($quantities as $key => $value) {
$month = [
$quantities[$key][0] => $quantities[$key][1]
];
$months[$quantities[$key][0]] = $quantities[$key][1];
print_r($month);
}
//Also print full array of months:
print_r($months);
Results are:
Pretty print:
<pre>Array
(
[0] => Array
(
[0] => Jan
[1] => 1
)
[1] => Array
(
[0] => Feb
[1] => 3
)
[2] => Array
(
[0] => Mar
[1] => 6
)
[3] => Array
(
[0] => Apr
[1] => 10
)
[4] => Array
(
[0] => May
[1] => 15
)
[5] => Array
(
[0] => Jun
[1] => 21
)
[6] => Array
(
[0] => Jul
[1] => 28
)
[7] => Array
(
[0] => Aug
[1] => 36
)
[8] => Array
(
[0] => Sep
[1] => 45
)
[9] => Array
(
[0] => Oct
[1] => 55
)
[10] => Array
(
[0] => Nov
[1] => 66
)
[11] => Array
(
[0] => Dec
[1] => 78
)
)
</pre>
Print out "list":
Array
(
[Feb] => 3
)
Array
(
[Mar] => 6
)
Array
(
[Apr] => 10
)
Array
(
[May] => 15
)
Array
(
[Jun] => 21
)
Array
(
[Jul] => 28
)
Array
(
[Aug] => 36
)
Array
(
[Sep] => 45
)
Array
(
[Oct] => 55
)
Array
(
[Nov] => 66
)
Array
(
[Dec] => 78
)
Or print one array (month as key)
Array
(
[Jan] => 1
[Feb] => 3
[Mar] => 6
[Apr] => 10
[May] => 15
[Jun] => 21
[Jul] => 28
[Aug] => 36
[Sep] => 45
[Oct] => 55
[Nov] => 66
[Dec] => 78
)
BR

You may create an array filled from 1 to 12 and apply the array_reduce to get your output.
<?php
class P {
public $m1 = 1;
public $m2 = 1;
public $m3 = 1;
public $m4 = 1;
public $m5 = 1;
public $m6 = 1;
public $m7 = 1;
public $m8 = 1;
public $m9 = 1;
public $m10 = 1;
public $m11 = 1;
public $m12 = 1;
public function __construct() {
}
}
$ppmpitem = new P();
$array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
$quantities = array_reduce($array, function ($carry, $item) use ($ppmpitem) {
$month = DateTime::createFromFormat('!m', $item)->format('M');
$carry['total'] += $ppmpitem->{"m" . $item};
$carry['quantities'][] = [$month, $carry['total']];
return $carry;
}, ['total' => 0, 'quantities' => []])['quantities'];
var_dump($quantities);

There are a number of ways to display a multidimensional array including use of the default PHP's print_r() function. Besides if you want a more precise way of accessing the elements and displaying them you can use a looping criteria such as for() or foreach(). Sample :
foreach($quantities as $qty){
print_r($qty);
}

Related

Get same index value of an array repeated time, based on a variable in php

We have an array in PHP like below:
Array
(
[0] => Array
(
[id] => 29
[name] => Testing1
)
[1] => Array
(
[id] => 30
[name] => Testing2
)
[2] => Array
(
[id] => 31
[name] => Testing3
)
)
We also have a variable $getvalue . We want to create a function (we will use the function in for loop) in which we pass above array and $getvalue. If $getvalue = 2 it should return key[0] 2 time, key[1] 2 time and key[2] 2 time like below.
[0] => Array
(
[id] => 29
[name] => Testing1
)
[0] => Array
(
[id] => 29
[name] => Testing1
)
[1] => Array
(
[id] => 30
[name] => Testing2
)
[1] => Array
(
[id] => 30
[name] => Testing2
)
[2] => Array
(
[id] => 31
[name] => Testing3
)
[2] => Array
(
[id] => 31
[name] => Testing3
)
If $getvalue = 1 it should return key[0] 1 time, key[1] 1 time and key[2] 1 time like below.
[0] => Array
(
[id] => 29
[name] => Testing1
)
[1] => Array
(
[id] => 30
[name] => Testing2
)
[2] => Array
(
[id] => 31
[name] => Testing3
)
Tried :
for($i = 0; $i<=count($array); $i++) {
foreach($array as $key => $val) {
if($i==$getvalue )
{
$a[] = $array[$i+1];
}
else
{
$a[] = $array[$i];
}
}
}
Also tried :
static function abc ($array,$getvalue)
{
foreach ($array as $key => $value) {
for ($i=0; $i <= $getvalue; $i++) {
return $arr[$i];
}
}
}
Each element of input array is added to the return value $getvalue times:
<?php
function repeatify( array $array, int $getvalue ): array {
$out = [];
if($getvalue <= 0) return $out;
foreach( $array as $element ){
foreach( range(0, $getvalue - 1) as $we_actualy_are_not_using_this_var )
$out[] = $element;
# Or alternatively with a `for` loop (i'll comment this out since i prefer an above code):
/*
for (
$we_actualy_are_not_using_this_var = 0;
$we_actualy_are_not_using_this_var < $getvalue;
$we_actualy_are_not_using_this_var++
) {
$out[] = $element;
}
*/
}
return $out;
}
$data = [
[
'id' => 29,
'name' => 'Testing1',
],
[
'id' => 30,
'name' => 'Testing2',
],
[
'id' => 31,
'name' => 'Testing2',
],
];
print '<pre>';
print_r( repeatify( $data, 0 ) );
print_r( repeatify( $data, 1 ) );
print_r( repeatify( $data, 2 ) );

Combined Strings and sum numeric two multidimensional arrays in PHP

I have below two arrays with strings and numbers,
I want to keep only one strings header and sum numeric value from each key value with another array.
I have tried many of the solutions available online but nothing found as required.
$array1 =
Array
(
[0] => Array
(
[0] => Out Of Warranty
[1] => Total Orders
[2] => Total Qty
[3] => Canceled Orders
)
[1] => Array
(
[0] => Today<br/>(04-26-2020)
[1] => 1
[2] => 1
[3] => 0
)
[2] => Array
(
[0] => Yesterday<br/>(04-25-2020)
[1] => 0
[2] => 0
[3] => 0
)
[3] => Array
(
[0] => This Week<br/>(04-20-2020 - 04-26-2020)
[1] => 22
[2] => 39
[3] => 0
)
[4] => Array
(
[0] => Last Week<br/>(04-13-2020 - 04-19-2020)
[1] => 7
[2] => 7
[3] => 0
)
[5] => Array
(
[0] => This Month<br/>(04-01-2020 - 04-26-2020)
[1] => 29
[2] => 46
[3] => 0
)
[6] => Array
(
[0] => This Year<br/>(01-01-2020 - 04-26-2020)
[1] => 30
[2] => 47
[3] => 0
)
)
$array2 =
Array
(
[0] => Array
(
[0] => Out Of Warranty
[1] => Total Orders
[2] => Total Qty
[3] => Canceled Orders
)
[1] => Array
(
[0] => Today<br/>(04-24-2020)
[1] => 10
[2] => 10
[3] => 0
)
[2] => Array
(
[0] => Yesterday<br/>(04-23-2020)
[1] => 7
[2] => 7
[3] => 0
)
[3] => Array
(
[0] => This Week<br/>(04-20-2020 - 04-24-2020)
[1] => 51
[2] => 51
[3] => 0
)
[4] => Array
(
[0] => Last Week<br/>(04-13-2020 - 04-19-2020)
[1] => 31
[2] => 31
[3] => 0
)
[5] => Array
(
[0] => This Month<br/>(04-01-2020 - 04-24-2020)
[1] => 93
[2] => 93
[3] => 0
)
[6] => Array
(
[0] => This Year<br/>(01-01-2020 - 04-24-2020)
[1] => 1281
[2] => 1281
[3] => 1
)
)
Expected output as Strings should be use only once and numbers should be added to each other.
For example output should be 6 index i.e sum of 6 index from array1 and array2 -
[6] => Array
(
[0] => This Year<br/>(01-01-2020 - 04-26-2020)
[1] => 1311
[2] => 1328
[3] => 1
)
If your arrays are always sorted in the same order:
$newItems = [];
foreach ($array1 as $key => $item) {
$newItems[] = [
$item[0],
$item[1] + $array2[$key][1],
$item[2] + $array2[$key][2],
$item[3] + $array2[$key][3],
];
}
If keys in arrays are in distinct orders:
$newItems = [];
foreach ($array1 as $item) {
$name = $item[0];
$newItems[$name] = $item;
}
foreach ($array2 as $item) {
$name = $item[0];
$newItems[$name][1] += $item[1];
$newItems[$name][2] += $item[2];
$newItems[$name][3] += $item[3];
}
// apply array_values to get 0-indexed array
$newItems = array_values($newItems);
Only iterate the elements that are necessary for your summing logic. Using 2 loops will be the most concise and deliberate way to sum columns [1], [2], and [3].
You can create a new output array, but merely adding the second array values to the first affords a simpler addition-assignment syntax.
Code: (Demo)
for ($i = 1, $size = count($array2); $i < $size; ++$i) { // don't iterate [0] subarray (headers)
for ($col = 1; $col <= 3; ++$col) { // don't iterate [0] element (name)
$array1[$i][$col] += $array2[$i][$col];
}
}
var_export($array1);
Output:
array (
0 =>
array (
0 => 'Out Of Warranty',
1 => 'Total Orders',
2 => 'Total Qty',
3 => 'Canceled Orders',
),
1 =>
array (
0 => 'Today<br/>(04-26-2020)',
1 => 11,
2 => 11,
3 => 0,
),
2 =>
array (
0 => 'Yesterday<br/>(04-25-2020)',
1 => 7,
2 => 7,
3 => 0,
),
3 =>
array (
0 => 'This Week<br/>(04-20-2020 - 04-26-2020)',
1 => 73,
2 => 90,
3 => 0,
),
4 =>
array (
0 => 'Last Week<br/>(04-13-2020 - 04-19-2020)',
1 => 38,
2 => 38,
3 => 0,
),
5 =>
array (
0 => 'This Month<br/>(04-01-2020 - 04-26-2020)',
1 => 122,
2 => 139,
3 => 0,
),
6 =>
array (
0 => 'This Year<br/>(01-01-2020 - 04-26-2020)',
1 => 1311,
2 => 1328,
3 => 1,
),
)

Creating Array inside another array using foreach loop php

Its been four hours I have search everywhere on google and SOF but unable to find the answer. This is what i have tried so far. Here is my code so far
$tmp_array = array();
foreach ($cms as $key => $val) {
$cDate = date('Ym', strtotime($val['day_date']));
$tmp_ids[] = $val['id'];
if (array_key_exists($cDate, $tmp_array)) {
$tmp_array[$cDate]['new_visitors'] += $val['new_visitors'];
$tmp_array[$cDate]['ids'] = $tmp_ids;
} else {
$tmp_array[$cDate]['new_visitors'] = $val['new_visitors'];
$tmp_array[$cDate]['ids'] = $tmp_ids;
}
}
its output is coming like this,
Array
(
[202001] => Array
(
[new_visitors] => 797
[ids] => Array
(
[0] => 31
[1] => 32
)
)
[202002] => Array
(
[new_visitors] => 461
[ids] => Array
(
[0] => 31
[1] => 32
[2] => 33
[3] => 34
)
)
)
but i want the result array like this,
Array
(
[202001] => Array
(
[new_visitors] => 797
[ids] => Array
(
[0] => 31
[1] => 32
)
)
[202002] => Array
(
[new_visitors] => 461
[ids] => Array
(
[0] => 33
[1] => 34
)
)
)
Any suggestions, what am i doing in my code?
The ids are basicall primary key of the table and the "new_visitors" are count of the visitor those who visit on my site. but i havent find any solution so far.
Here is my $cms array.
Array
(
[0] => Array
(
[id] => 31
[day_date] => 2020-01-30 00:00:00
[new_visitors] => 459
)
[1] => Array
(
[id] => 32
[day_date] => 2020-01-31 00:00:00
[new_visitors] => 338
)
[2] => Array
(
[id] => 33
[day_date] => 2020-02-01 00:00:00
[new_visitors] => 242
)
[3] => Array
(
[id] => 34
[day_date] => 2020-02-02 00:00:00
[new_visitors] => 219
)
)
Thank you misorude, your comment worked
$tmp_array = array();
foreach ($cms as $key => $val) {
$cDate = date('Ym', strtotime($val['day_date']));
if (array_key_exists($cDate, $tmp_array)) {
$tmp_array[$cDate]['new_visitors'] += $val['new_visitors'];
$tmp_array[$cDate]['ids'][] = $val['id'];
} else {
$tmp_array[$cDate]['new_visitors'] = $val['new_visitors'];
$tmp_array[$cDate]['ids'][] = $val['id'];
}
}
$arr = [
['id' => 31 ,'day_date'=> "2020-01-30 00:00:00", 'new_visitors' => 459],
['id' => 32 ,'day_date'=> "2020-01-31 00:00:00", 'new_visitors' => 338],
['id' => 33 ,'day_date'=> "2020-02-01 00:00:00", 'new_visitors' => 242],
['id' => 34 ,'day_date'=> "2020-02-02 00:00:00", 'new_visitors' => 219]
];
echo "<pre>";
print_r($arr);
$data = [];
$add_visitor = 0;
$day_date = '';
foreach($arr as $arr_value){
if(date('Ym', strtotime($arr_value['day_date'])) != $day_date){
$add_visitor = 0;
}
$add_visitor += $arr_value['new_visitors'];
$data[date('Ym', strtotime($arr_value['day_date']))]['new_visitors'] = $add_visitor;
$data[date('Ym', strtotime($arr_value['day_date']))]['ids'][] = $arr_value['id'];
$day_date = date('Ym', strtotime($arr_value['day_date']));
}
print_r($data);

PHP array - Sum value of the same key when key are number [duplicate]

This question already has answers here:
PHP Array Group by one field and Sum up two fields [duplicate]
(2 answers)
Closed 4 months ago.
My situation is similar to this thread :
Associative array, sum values of the same key
However in my case all keys are number.
I would like to reduce / combine array where key 0 is similar and make a sum of all other keys.
Here is my original array :
Array
(
[0] => Array
(
[0] => 093042
[1] => 3
[2] => 0
[4] => 0
)
[1] => Array
(
[0] => 222032
[1] => 0
[2] => 13
[4] => 0
)
[2] => Array
(
[0] => 222032
[1] => 0
[2] => 0
[4] => 15
)
[3] => Array
(
[0] => 152963
[1] => 45
[2] => 0
[4] => 0
)
[4] => Array
(
[0] => 222032
[1] => 0
[2] => 7
[4] => 0
)
)
and here is the output i need :
Array
(
[0] => Array
(
[0] => 093042
[1] => 3
[2] => 0
[4] => 0
)
[1] => Array
(
[0] => 222032
[1] => 0
[2] => 20
[4] => 15
)
[2] => Array
(
[0] => 152963
[1] => 45
[2] => 0
[4] => 0
)
)
The solution of other thread is not working because they use the key name and i don't know how i can adapt this to my situation.
Please if you can give me an example of working solution.
REPLY :
For now i try something like that : Take from other thread
$sum = array_reduce($data, function ($a, $b) {
if (isset($a[$b[0]])) {
$a[$b[0]]['budget'] += $b['budget'];
}
else {
$a[$b[0]] = $b;
}
return $a;
});
But this example look is only for key named budget but in my case is number and i have 3 key [1] [2] [3] how can't sum key 1,2,4 where key 0 is similar
This should work for you:
Basically I just loop through your array and check if there is already an element in $result with the key of the first element of $v. If not I initialize it with an array_pad()'ed array of 0's + the current array of the iteration of the foreach loop.
And after this I loop through each element of $v expect the first one and add it to the result array.
At the end I just reindex the result array with array_values().
<?php
foreach($arr as $v){
if(!isset($result[$v[0]]))
$result[$v[0]] = array_pad([$v[0]], count($v), 0);
$count = count($v);
for($i = 1; $i < $count; $i++)
$result[$v[0]][$i] += $v[$i];
}
$result = array_values($result);
print_r($result);
?>
output:
Array
(
[0] => Array
(
[0] => 093042
[1] => 3
[2] => 0
[3] => 0
)
[1] => Array
(
[0] => 222032
[1] => 0
[2] => 20
[3] => 15
)
[2] => Array
(
[0] => 152963
[1] => 45
[2] => 0
[3] => 0
)
)
try this
$data = Array
(
0 => Array
(
0 => 93042,
1 => 3,
2 => 0,
4 => 0,
),
1 => Array
(
0 => 222032,
1 => 0,
2 => 13,
4 => 0,
),
2 => Array
(
0 => 222032,
1 => 0,
2 => 0,
4 => 15,
),
3 => Array
(
0 => 152963,
1 => 45,
2 => 0,
4 => 0,
),
4 => Array
(
0 => 222032,
1 => 0,
2 => 7,
4 => 0,
),
);
var_dump($data);
// grouping
$tab1 = array();
foreach ($data as $e) {
if (!isset($tab1[$e[0]])) {
$tab1[$e[0]] = array();
}
$tab1[$e[0]][] = $e;
}
//var_dump($tab1);
// summing
$tabSum = array();
foreach ($tab1 as $id => $t) {
foreach ($t as $e) {
unset($e[0]);
if (!isset($tabSum[$id])) {
$tabSum[$id] = $e;
} else {
foreach ($e as $key => $value) {
$tabSum[$id][$key] += $value;
}
}
}
}
var_dump($tabSum);

Create Array From Current Array using PHP

This is the result of array after i build it using array_push function from mssql result.
Array
(
[0] => Array
(
[STICKER] => FALCON
[MONTH] => 1
[JUM] => 65826210.00
)
[1] => Array
(
[STICKER] => FALCON
[MONTH] => 2
[JUM] => 68070573.00
)
[2] => Array
(
[STICKER] => FALCON
[MONTH] => 3
[JUM] => 99053067.60
)
[3] =>
[4] => Array
(
[STICKER] => HRD
[MONTH] => 2
[JUM] => 1521400.00
)
[5] => Array
(
[STICKER] => HRD
[MONTH] => 3
[JUM] => 2093200.00
)
)
I need to convert array above into this structure:
Array
(
[0] => Array
(
[0] =>
[1] => 1
[2] => 2
[3] => 3
)
[1] => Array
(
[0] => FALCON
[1] => 65826210.00
[2] => 68070573.00
[3] => 99053067.60
)
[2] => Array
(
[0] => HRD
[1] => 0
[2] => 1521400.00
[3] => 2093200.00
)
)
Note:
Array[0] values would be 1,2,3 (this is actualy month, i just input up to 3 in order to get the code not too long. but it will be up to 12 (Jan - Dec)).
If from original array, there is none value (example from array[3]), then it will be convert to new array[2]->[1] with value 0.
Any help would be very appreciated.
Thanks all!.
Try this,
If any month is not mentioned from stickers the jum considered as 0,
$array = array(
array('STICKER' => 'FALCON', 'MONTH' => 1, 'JUM' => 65826210.00),
array('STICKER' => 'FALCON', 'MONTH' => 2, 'JUM' => 68070573.00),
array('STICKER' => 'FALCON', 'MONTH' => 3, 'JUM' => 99053067.60),
array(),
array('STICKER' => 'HRD', 'MONTH' => 2, 'JUM' => 1521400.00),
array('STICKER' => 'HRD', 'MONTH' => 3, 'JUM' => 2093200.00),
);
$result[0][] = '';
foreach ($array as $key => $res) {
if (!empty($res)) {
$result[0][$res['MONTH']] = $res['MONTH'];
$result1[$res['STICKER']][$res['MONTH']] = $res['JUM'];
}
}
foreach ($result1 as $key => $res) {
$fin = array();
foreach ($res as $key1 => $re) {
foreach ($result[0] as $key2 => $month) {
if ($month != '') {
if (array_key_exists($month, $res)) {
if (!array_key_exists($month, $fin) && $month == $key1) {
$fin[$month] = $re;
}
} else {
$fin[$month] = 0;
}
}
}
}
$result[] = array_merge(array($key), $fin);
}
echo'<pre>';
print_r($result);
echo'<pre>';
Result:
Array
(
[0] => Array
(
[0] =>
[1] => 1
[2] => 2
[3] => 3
)
[1] => Array
(
[0] => FALCON
[1] => 65826210
[2] => 68070573
[3] => 99053067.6
)
[2] => Array
(
[0] => HRD
[1] => 0
[2] => 1521400
[3] => 2093200
)
)
I hope this is used to achieve your output(you mentioned in above question)!!
try something like this
not the issue with the empty array i could not understand how the program would know that it is STICKER HRD so it will be filled with zero.But you could later check if every month "isset" and if it is not act as it is zero
$arr1=array(
array('STICKER'=>'FALCON','MONTH'=>1,'JUM'=>65826210.00),
array('STICKER'=>'FALCON','MONTH'=>2,'JUM'=>68070573.00),
array('STICKER'=>'FALCON','MONTH'=>3,'JUM'=>99053067.60),
array(),
array('STICKER'=>'HRD','MONTH'=>2,'JUM'=>1521400.00),
array('STICKER'=>'HRD','MONTH'=>3,'JUM'=>2093200.00),
);
$arr2=array();
$arr3=array();
$arr2[0][0]="";
foreach($arr1 as $key => $val){
if(!empty($val)){
$arr2[0][$val['MONTH']]=$val['MONTH'];
//group each STICKER
$arr3[$val['STICKER']][]=$val['JUM'];
}
}
//transfer the grouped data to arr2
foreach($arr3 as $key => $val){
$tmp_arr=array($key);
$arr2[]=array_merge($tmp_arr,$val);
}
print_r($arr2);

Categories