Dynamic associative Array - list, count, sum, min, max - php

I've got an array with about 40 keys. I'd like to have a small function that returns a summary array.
Right now I've got the following that works:
foreach ($all_data as $value){
$new_array[ $value['location'] ][ $value['manufacturer'] ][ $value['model'] ] += 1;
}
This returns an array with everything I need. However, the location, manufacturer and model could be changed up for a bunch of other values.
what I am trying to do is have something simple as:
$new_array = summarize($all_data,array('location','manufacturer','model','count'),array('list','list','list','count') );}
where this summarize function would build the call. I think I just need a bit of help on how to get it to run the string as code for this array. Otherwise I get
$current_selection = "[ $row_item['location'] ][ $row_item['manufacturer'] ][ $row_item['model'] ]"
$return_array{$current_selection} += 1;
Where the end goal is to have a function like:
function summarize($data_array, $fields_array, $process_array){
//data_array = associative multi-dimensional data array
//fields = values to pull from the data_array
//process = array specifying whether to list, sum, count, average, max, min
$return_array = array();
$current_selection = "";
foreach($fields_array as $field){
$current_selection .= '[ $row_item[\'' . $field . '\'] ]';
}
foreach ($data_array as $row_item){
//dynamic = DOES NOT WORK
$return_array[$current_selection] += 1;//eval? create function? abstract?
//another attempt
${'return_array' . $current_selection} += 1;
//Manual = Does work
//$return_array[ $row_item['location'] ][ $row_item['manufacturer'] ][ $row_item['model'] ] += 1;
}
}
Thanks for any help on how to do an indirect reference.
JC
RESOLUTION
The final version that managed to resolve this looks like the following, thanks to user: check, for getting me on the correct path.
function summarize($data_array, $fields_array, $process_array){
$return_array = array();
$i = 0;
foreach ($data_array as $row){
$ii = 0;
$temp = array();
$temp2 = array();
foreach($fields_array as $key=>$field){
if($process_array[$ii] == 'list') $temp[$ii] = $row[$field];
if($process_array[$ii] == 'count') $temp2[$ii] = 1;
if($process_array[$ii] == 'sum') $temp2[$ii] = $row[$field];
$ii++;
}
$unique = true;
$ii = 0;
foreach($return_array as $row2){
if(array_intersect_key($row2,$temp) == $temp){//$row2 == $temp){
$unique = false;
break;
}
$ii++;
}
if($unique){
$return_array[$i] = $temp;
if(!empty($temp2)) $return_array[$i] = array_merge($temp,$temp2);
$i++;
}else{
if(!empty($temp2)){
foreach($temp2 as $key => $value){
if($process_array[$key] == 'sum') $temp2[$key] = $return_array[$ii][$key] + $value;
if($process_array[$key] == 'count') $temp2[$key] = $return_array[$ii][$key] + 1;
if($process_array[$key] == 'max') $temp2[$key] = ($return_array[$ii][$key] < $value) ? $value : $return_array[$ii][$key];
if($process_array[$key] == 'min') $temp2[$key] = ($return_array[$ii][$key] > $value) ? $value : $return_array[$ii][$key];
//TODO:(JC) 'average' - need to create a count field if not present (or always despite and assume overhead of extra computations).
// - then just calculate the 'sum' and divide by the counter as a last step before returning the array.
}
$return_array[$ii] = array_merge($temp,$temp2);
}
}
}
print_r($return_array);
return $return_array;
}
Which gives the following result:
/*
CALL: summarize($data,array('location','manufacturer','model','model','volume','colourvolume'),array('list','list','list','count','sum','sum') );
[0] = location
[1] = manufacturer
[2] = model
[3] = model count
[4] = mono volume sum
[5] = colour volume sum
*/
Array
(
[0] => Array
(
[0] =>
[1] => HP
[2] => LaserJet 4000
[3] => 3
[4] => 3000
[5] => 0
)
...
[17] => Array
(
[0] => Room 114
[1] => CANON
[2] => iR3235
[3] => 1
[4] => 4012
[5] => 0
)
[18] => Array
(
[0] => Room 115
[1] => LEXMARK
[2] => T652
[3] => 1
[4] => 20
[5] => 0
)
)

alternatively, if I assume that's $field_array contains sequentially key fields from root to sub key, you can loop your $field_array within $data_array loop
function summarize($data_array, $fields_array, $process_array){
$return_array = array();
foreach ($data_array as $row){
$temp = array();
foreach($fields_array as $key=>$field){
$temp = $key==0?$row[$field]:$temp[$field];
}
if(!empty($temp)) $return_array[] = $temp;
}
return $return_array;
}
and this is my array, will summarize with these function
$array = array(
array("multi"=>array("dimensional"=>array("array"=>"foo1"))),
array("multi"=>array("dimensional"=>array("array"=>"foo2"))),
array("multi"=>array("dimensional"=>array("array"=>"foo3"))),
array("multi"=>array("dimensional"=>array("array"=>"foo4"))),
array("multi"=>array("dimensional"=>array("array"=>"foo5"))),
array("multi"=>array("dimensional"=>array("array"=>"foo6"))),
array("multi"=>array("dimensional"=>array("array"=>"foo7"))),
array("multi"=>array("dimensional"=>array("array"=>"foo8"))),
array("multi"=>array("dimensional"=>array("array"=>"foo9")))
);
print_r(summarize($array,array("multi","dimensional","array"),NULL));
Ouput
Array ( [0] => foo1 [1] => foo2 [2] => foo3 [3] => foo4 [4] => foo5 [5] => foo6 [6] => foo7 [7] => foo8 [8] => foo9 )

Related

Combine same indexes of array

I have an array which as dynamic nested indexes in e.g. I am just using 2 nested indexes.
Array
(
[0] => Array
(
[0] => 41373
[1] => 41371
[2] => 41369
[3] => 41370
)
[1] => Array
(
[0] => 41378
[1] => 41377
[2] => 41376
[3] => 41375
)
)
Now I want to create a single array like below. This will have 1st index of first array then 1st index of 2nd array, 2nd index of first array then 2nd index of 2nd array, and so on. See below
array(
[0] =>41373
[1] => 41378
[2] => 41371
[3] => 41377
[4] => 41369
[5] => 41376
[6] => 41370
[7] => 41375
)
You can do something like this:
$results = [];
$array = [[1,2,3,4], [1,2,3,4], [1,2,3,4]];
$count = 1;
$size = count($array)-1;
foreach ($array[0] as $key => $value)
{
$results[] = $value;
while($count <= $size)
{
$results[] = $array[$count][$key];
$count++;
}
$count = 1;
}
I think you need something like this:
function dd(array $arrays): array
{
$bufferArray = [];
foreach($arrays as $array) {
$bufferArray = array_merge_recursive($bufferArray, $array);
}
return $bufferArray;
}
$array1 = ['41373','41371','41369','41370'];
$array2 = ['41378','41377', '41376', '41375'];
$return = array();
$count = count($array1)+count($array2);
for($i=0;$i<($count);$i++){
if($i%2==1){
array_push($return, array_shift($array1));
}
else {
array_push($return, array_shift($array2));
}
}
print_r($return);
first count the arrays in the given array, then count the elements in the first array, than loop over that. All arrays should have the same length, or the first one should be the longest.
$laArray = [
['41373','41371','41369','41370'],
['41378', '41377', '41376', '41375'],
['43378', '43377', '43376', '43375'],
];
$lnNested = count($laArray);
$lnElements = count($laArray[0]);
$laResult = [];
for($lnOuter = 0;$lnOuter < $lnElements; $lnOuter++) {
for($lnInner = 0; $lnInner < $lnNested; $lnInner++) {
if(isset($laArray[$lnInner][$lnOuter])) {
$laResult[] = $laArray[$lnInner][$lnOuter];
}
}
}
this would be the simplest solution:
$firstarr = ['41373','41371','41369','41370'];
$secondarr = ['41378','41377','41376','41375'];
$allcounged = count($firstarr)+count($secondarr);
$dividedintotwo = $allcounged/2;
$i = 0;
while ($i<$dividedintotwo) {
echo $firstarr[$i]."<br>";
echo $secondarr[$i]."<br>";
$i++;
}

Split array but sum of each array not to exceed a max value else push to next array index

I have two arrays, Array 1 being a donor array which has a series of values (not necessarily equal values as in my example). Array 2 is the desired result and would store a series of sub arrays with values from Array 1 where each sub array's total sum would not exceed 25. If it does, the excess would get pushed to the next index in Array 2 where the rules would also apply.
Donor array (Array 1):
$a1=array(10,10,10,10,10,10,10,10,10,10);
Desired output (Array 2):
Array
(
[0] => 10,10,5
[1] => 5,10,10
[2] => 10,10,5
[3] => 5,10,10
)
Here the code I tried but it gets an error:
Notice: Undefined offset: 10...etc.
$a1=array(10,10,10,10,10,10,10,10,10,10);
$a2=array();
$count=count($a1);
for($i=0;$i<$count;$i++){
$a2count=array_sum($a2);
if($a2count>25){
$i=$i+1;
$a2[$i]=$a1[$i];
}
else{
$a2[$i]=$a1[$i];
}
}
print_r($a2);
I don't know what logic to implement and get result I'm looking for.
Mayhaps something like this will work for you. I will notate so it's not just a copy-and-paste answer. Maybe someone will get some insight on it to improve it in the future:
function slitArray($a1,$num = 25)
{
# Used to store the difference when the value exceeds the max
$store = 0;
# Storage container that will be built using sums/diffs
$new = array();
# Loop through the main array
foreach($a1 as $value) {
# If the last key/value pair in our return array is an array
if(is_array(end($new)))
# Add up the values in that array
$sum = array_sum(current($new));
else
# If not array, no values have been stored yet
$sum = 0;
# This just gets the last key
$count = (count($new)-1);
# Assign last key
$i = ($count <= 0)? 0 : $count;
# If the sum of the current storage array plus the value
# of the current array is greater than our max value
if(($sum + $value) > $num) {
# Take max and remove the current total of storage array
$use = ($num-$sum);
# Take what's left and remove it from the current value
$store = ($value-$use);
# If the current stored value (the value we want to push to
# the next storage k/v pair) is more than the max allowed
if($store > $num) {
# Takes a value, checks if it's greater than max,
# and if it is, breaks the value up by max as a divider
$divide = function($store,$num)
{
if($store > $num) {
$count = ceil($store/$num);
for($i=0; $i<$count; $i++) {
$new[] = ($store > $num)? $num : $store;
$store -= $num;
}
return $new;
}
else
return array($store);
};
# This should either be an array with 1 or more values
$forward = $divide($store,$num);
# Do a look forward and add this excess array into our
# current storage array
$a = $i;
foreach($forward as $aVal) {
$new[$a+=1][] = $aVal;
}
}
# If the store value is less than our max value, just add
# it to the next key in this storage array
else {
$new[$i+1][] = $store;
# Reset the storage back to 0, just incase
$store = 0;
}
}
# Set the current "use" value as the current value in our
# from-array. Since it doesn't exceed the max, it just gets
# added to the storage array
else
$use = $value;
# Sometimes the math makes $use 0, keep that out of the
# storage array. The $use value is the current value to add at
# the time of iteration. Previous storage values are added as
# future-keys
if($use > 0)
$new[$i][] = $use;
}
# Return the final assembled array
return $new;
}
# To use, add array into function
$a1 = array(10,10,10,10,10,10,10,10,10,10);
# to split using different max value, just add it to second arg
# example: slitArray($a1,20);
print_r(slitArray($a1));
Gives you:
Array
(
[0] => Array
(
[0] => 10
[1] => 10
[2] => 5
)
[1] => Array
(
[0] => 5
[1] => 10
[2] => 10
)
[2] => Array
(
[0] => 10
[1] => 10
[2] => 5
)
[3] => Array
(
[0] => 5
[1] => 10
[2] => 10
)
)
An array input of:
$a1 = array(23,2,71,23,50,2,3,4,1,2,50,75);
Gives you:
Array
(
[0] => Array
(
[0] => 23
[1] => 2
)
[1] => Array
(
[0] => 25
)
[2] => Array
(
[0] => 25
)
[3] => Array
(
[0] => 21
[1] => 4
)
[4] => Array
(
[0] => 19
[1] => 6
)
[5] => Array
(
[0] => 25
)
[6] => Array
(
[0] => 19
[1] => 2
[2] => 3
[3] => 1
)
[7] => Array
(
[0] => 3
[1] => 1
[2] => 2
[3] => 19
)
[8] => Array
(
[0] => 25
)
[9] => Array
(
[0] => 6
[1] => 19
)
[10] => Array
(
[0] => 25
)
[11] => Array
(
[0] => 25
)
[12] => Array
(
[0] => 6
)
)
Here you go: The logic is not so hard. Hope it helps.
<?php
$a1=array(10,10,10,10,10,10,10,10,10,10);
$a2 = [];
$a3 = [];
$m = 0;
for($i = 0; $i < count($a1); ++$i){
$m += $a1[$i];
if($m > 25){
$n = $m % 25;
if(array_sum($a2) != 25){
$a2[] = $n;
}
$a3[] = implode(',', $a2);
$a2 = [];
$m = $n;
$a2[] = $n;
} else{
$a2[] = $a1[$i];
}
}
$a3[] = implode(',', $a2);
print_r($a3);
?>
The final code for this question
<?php
function slitArray($a1,$num = 25)
{
$store = 0;
$new = array();
foreach($a1 as $value) {
if(is_array(end($new)))
$sum = array_sum(current($new));
else
$sum = 0;
$count = (count($new)-1);
$i = ($count <= 0)? 0 : $count;
if(($sum + $value) > $num) {
$use = ($num-$sum);
$store = ($value-$use);
if($store > $num) {
$divide = function($store,$num)
{
if($store > $num) {
$count = ceil($store/$num);
for($i=0; $i<$count; $i++) {
$new[] = ($store > $num)? $num : $store;
$store -= $num;
}
return $new;
}
else
return array($store);
};
$forward = $divide($store,$num);
$a = $i;
foreach($forward as $aVal) {
$new[$a+=1][] = $aVal;
}
}
else {
$new[$i+1][] = $store;
$store = 0;
}
}
else
$use = $value;
if($use > 0)
$new[$i][] = $use;
}
return $new;
}
$a1 = array(10,20,30,40,50,60);
$arr=slitArray($a1);
print_r($arr);
?>
Let me help you a bit using Pseudocode:
ar1 = {10,10,10,20,40,[0]=>1,[0]=>3,[0]=>4};
ar2 = new array (ar.length) \\ worst case
int c = 0; \\current
foreach (ar1 as $value){
ar2 [c]+=ar1[i];
if (ar2 [c]>25){ c++;}
}
Logic behind the code:
Add the value of ar1[i] to the current ar2 value till it passes your limit (25 in this case). If it exceeds you boundary, than move to the next value in the goal array. The worst case would be, that every value is over 25, so it would be an exact copy of the original array.
Here the php code:
$ar1=array(10,10,10,10,10,10,10,10,10,10);
$ar2 = array(0,0,0,0,0,0,0,0,0,0);
$c = 0;
foreach( $ar1 as $key => $value ){
$ar2[$c]=$value+$ar2[$c];
if ($ar2[$c]>25){$c++;}
}

Create an array from two array PHP

i have two arrays
$value_array = array('50','40','30','20','10');
$customer = array('300','200','100');
i want to distribute the value array to customers based on the value of customers that is taken as limit.adding values by checking it wont cross the limit that is 300 , 200 and 100.
but customer array not working one direction it should work first forward and then backward like that
i want to produce an array in form of
Array
(
[0] => Array
(
[0] => 50
)
[1] => Array
(
[0] => 40
[1] => 10
)
[2] => Array
(
[0] => 30
[1] => 20
)
)
After completing customer loop first time it should start from last to first. both array count will change , i mean count.
value array should check 50 -> 300 , 40->200, 30->100 then from last ie, 20 ->100, 10->200 etc.
I tried like
$i = 0;
while($i < count($customer)){
foreach($value_array as $k=>$value){
$v = 0;
if($value <= $customer[$i]){
$customer2[$i][] = $value;
unset($value_array[$k]);
$v = 1;
}
if($v ==1){
break;
}
}
//echo $i."<br/>";
if($i == (count($customer)-1) && (!empty($value_array))){
$i = 0;
$customer = array_reverse($customer, true);
}
$i++;
}
echo "<pre>";
print_r($customer2);
$valueArray = array('50','40','30','20','10','0','-11');
$customer = array('300','200','100');
function parse(array $valueArr, array $customerArr)
{
$customerCount = count($customerArr);
$chunkedValueArr = array_chunk($valueArr, $customerCount);
$temp = array_fill(0, $customerCount, array());
$i = 0;
foreach ($chunkedValueArr as $item) {
foreach ($item as $key => $value) {
$temp[$key][] = $value;
}
$temp = rotateArray($temp);
$i++;
}
// if $i is odd
if ($i & 1) {
$temp = rotateArray($temp);
}
return $temp;
}
function rotateArray(array $arr)
{
$rotatedArr = array();
//set the pointer to the last element and add it to the second array
array_push($rotatedArr, end($arr));
//while we have items, get the previous item and add it to the second array
for($i=0; $i<sizeof($arr)-1; $i++){
array_push($rotatedArr, prev($arr));
}
return $rotatedArr;
}
print_r(parse($valueArray, $customer));
returns:
Array
(
[0] => Array
(
[0] => 50
[1] => 0
[2] => -11
)
[1] => Array
(
[0] => 40
[1] => 10
)
[2] => Array
(
[0] => 30
[1] => 20
)
)

Need some help making a php search tree

Im making a tree to store words and an associated number array in php. I need it to look something like this:
Words: apple, ant
[a] => Array
(
[p] => Array
(
[p] => Array
(
[l] => Array
(
[e] => Array
(
[0] => Array
(
[0] => 0
[1] => 0
[2] => 1
[3] => 2
[4] => 3
[5] => 4
)
)
)
)
)
[n] => Array
(
[t] => Array
(
[0] => Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 0
[4] => 0
[5] => 4
)
)
)
)
Of course apple and ant need to share the same [a] index. Im close, but I cant figure out how to properly keep track of the tree index so 'apple' gets into the tree fine but 'ant' is inserted as 'nt'. Heres my code at the moment:
private function insertWordsIntoTree()
{
foreach ($this->words as $word)
{
$characters = preg_replace('/[0-9]+/', '', $words);
$points = $this->getPoints($word);
$this->tree = $this->buildTree($characters, $points, $this->tree);
}
print_r($this->tree);
}
private function buildTree($characters, array $points, array $tree)
{
for ($i = 0; $i < strlen($characters); $i++)
{
$character = $characters[$i];
$remaining_characters = substr($characters, $i + 1);
if (strlen($characters) === 1)
{
$child = [];
$child[$character] = [$points];
return $child;
}
elseif (!isset($tree[$character]))
{
$tree[$character] = $this->buildTree($remaining_characters, $points, []);;
break;
}
else
{
$this->buildTree($remaining_characters, $points, $tree[$character]);
}
}
return $tree;
}
Im pretty sure the problem is at the else statement...I dont think Im keeping track of the current tree index properly. Any help would be much appreciated.
Here's a simple approach that passes the recursion off to php:
$tree = array();
foreach($words as $word) {
$characters = array_reverse(str_split($word));
$temp = array();
foreach($characters as $index => $character) {
if($index == 0) {
$temp[] = getPoints($word);
}
$temp = array(
$character => $temp
);
}
$tree = array_merge_recursive($tree, $temp);
}

Counting an eliminating duplicate associative values in an array

I have the following issue, I have an array with the name $data
Within this array I have something like
[6] => Array
(
[code] => 642
[total] => 1708
)
[7] => Array
(
[code] => 642
[total] => 53
)
[8] => Array
(
[code] => 642
[total] => 1421
)
In some elements the code value is the same, now what I want to do is merge all the elements with the same code value together, and adding the totals together. I tried doing this in a foreach loop, but does not seem to work.
I do something like this
$old_lc = null;
$old_lcv = 0;
$count = 0;
$dd = null;
foreach($data as $d){
if($d['code'] == $old_lc){
$d['total'] = $d['total'] + $old_lcv;
$count--;
$dd[$count]['code'] = $d['code'];
$dd[$count]['total'] = $d['total'];
}else{
$dd[$count]['code'] = $d['code'];
$dd[$count]['total'] = $d['total'];
$count++;
}
$old_lc = $d['code'];
$old_lcv = $d['total'];
}
$data = $dd;
But this does not seem to work. Also I need the $data array to keep the keys, and should remain in the same format
$result = array();
foreach($ary as $elem) {
$code = $elem['code'];
$total = $elem['total'];
if(!isset($result[$code]))
$result[$code] = 0;
$result[$code] += $total;
}
This code translates the above array into an array of code => total.
$out = array();
foreach ($data as $k => $v) {
$out[$v['code']] += $v['total'];
}
It is worth noting that on certain settings this will generate a warning about undefined indexes. If this bothers you, you can use this alternate version:
$out = array();
foreach ($data as $k => $v) {
if (array_key_exists($v['code'], $out)) {
$out[$v['code']] += $v['total'];
} else {
$out[$v['code']] = $v['code'];
}
}
This turns it back into something like the original, if that's what you want:
$output = array();
foreach ($out as $code => $total) {
$output[] = array('code' => $code, 'total' => $total);
}
Note: the original keys of $data aren't maintained but it wasn't stated that this was a requirement. If it is, it needs to be specified how to reconstruct multiple elements that have the same code.
[6] => Array
(
[code] => 642
[total] => 1708
)
[7] => Array
(
[code] => 642
[total] => 53
)
[8] => Array
(
[code] => 642
[total] => 1421
)
$data_rec = array();
$data = array();
foreach($data_rec as $key=>$rec)
{
$data[$key]+= $rec[$key];
}
print_r($data);

Categories