<?php
$quantity = array(1,2,3,4,5,6,7,8,9,10,11,12,1,14,2,16);
// Create a new array
$output_array = array();
$sum_quantity = 0;
$i = 0;
foreach ($quantity as $value) {
if($sum_quantity >= 35) {
$output_array[$i][] = $value;
}
$sum_quantity = $sum_quantity + $value;
}
print_r($output_array);
When summmary each item >= 35 will auto create child array
array(
[0] => array(1, 2, 3, 4, 5, 6, 7),
[1] => array(8, 9, 10),
[2] => array(11, 12, 1),
[3] => array(14, 2, 16)
)
$quantity = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 14, 2, 16);
// Create a new array
$output_array = array();
$current_array = array();
$current_sum = 0;
foreach ($quantity as $value) {
$current_sum += $value;
if ($current_sum >= 35) {
$output_array[] = $current_array;
$current_array = array();
$current_sum = $value;
}
$current_array[] = $value;
}
$output_array[] = $current_array;
print_r($output_array);
// Output:
// Array
// (
// [0] => Array
// (
// [0] => 1
// [1] => 2
// [2] => 3
// [3] => 4
// [4] => 5
// [5] => 6
// [6] => 7
// )
// [1] => Array
// (
// [0] => 8
// [1] => 9
// [2] => 10
// )
// [2] => Array
// (
// [0] => 11
// [1] => 12
// [2] => 1
// )
// [3] => Array
// (
// [0] => 14
// [1] => 2
// [2] => 16
// )
// )
I see,maybe your desired answer is as follows,
$quantity = array(1,2,3,4,5,6,7,8,9,10,11,12,1,14,2,16);
// Create a new array
$output_array = array();
$sum_quantity = 0;
$i = 0;
for each($quantity as $value) {
$sum_quantity += $value;
if($sum_quantity >= 35) {
$i++;
$output_array[$i][] = $value;
$sum_quantity = $value;
}else{
$output_array[$i][] = $value;
}
}
print_r($output_array);
I have tried test,It's ok.
Related
I have an array that can contain anything from 4 to 4000 entries, I have to evenly assign the amounts across 4 people. I am struggling just to get my code to do as I need.
As you can see my allocation to the arrays are not as desired.
Array ( [0] => Array ( [0] => 80 [7] => 40 [8] => 50 )
[1] => Array ( [1] => 80 )
[2] => Array ( [2] => 70 [6] => 30 )
[3] => Array ( [3] => 60 [5] => 40 )
)
array 0 has total of 150
array 1 has total of 80
array 2 has total of 100
array 3 has total of 100
Code:
<?php
arrayBuilder();
function arrayBuilder()
{
$list_of_items = [80, 20, 30, 40, 50, 60, 70, 80];
rsort($list_of_items);
$number_of_cont = 4;
$weight_of_items = array_sum($list_of_items);
$weight_per_cont = ($weight_of_items/$number_of_cont);
$containers = [];
$sumArray = $newArray = [];
$containersSorted = buildArray($list_of_items,$number_of_cont,$containers,$weight_per_cont);
$itemsNotAdded = itemsNotINArray($list_of_items, $containersSorted);
foreach ($containersSorted as $k => $subArray) {
foreach ($subArray as $id => $value) {
if(isset($sumArray[$k])) {
$sumArray[$k] += $value;
}else{
$sumArray[$k] = $value;
}
}
}
sort($sumArray);
$itemsNotAdded = array_values($itemsNotAdded);
foreach($itemsNotAdded as $key => $value){
foreach($sumArray as $minkey => $minval){
if($minkey == $key) {
$containersSorted[$key][] = $value;
unset($itemsNotAdded[$key]);
}
}
}
print_r($containersSorted);
};
function itemsNotINArray($list_of_items, $containersSorted){
foreach($containersSorted as $conid => $conval){
foreach($list_of_items as $key => $value){
if(key_exists($key,$conval)){
unset($list_of_items[$key]);
continue;
}
}
}
return $list_of_items;
};
function getMisMatchKey($itemsNotAdded, $containersSorted){
}
function buildArray($list_of_items,$number_of_cont,$containers,
$weight_per_cont){
foreach($list_of_items as $key => $item) {
for ($i = 0; $i < $number_of_cont; $i++) {
$total = (isset($containers[$i])) ? array_sum($containers[$i]) : 0;
if (($total + $item) < $weight_per_cont) {
$containers[$i][$key] = $item;
break;
}
}
}
return $containers;
};
?>
Should have worked it out evenly
Array ( [0] => Array ( [0] => 80 [7] => 20 )
[1] => Array ( [1] => 80 [6] => 30 )
[2] => Array ( [2] => 70 [8] => 40 )
[3] => Array ( [3] => 60 [5] => 50 )
)
This splits the array into arrays with pairs of the value 80:
public function action_binAllocation()
{
$list_of_items = [80, 20, 30, 40, 50, 60, 70, 80, 10, 70];
$sum = 80;
$evenlySortedArray = $this->findPairsInArrayWhereSum($sum, $list_of_items);
print_r($evenlySortedArray);
}
public function findPairsInArrayWhereSum($sum, $arr = [])
{
$s = [];
$evenlyDistributedArrays = [];
for ($i = 0; $i < count($arr); $i++) {
$temp = $sum - $arr[$i];
$s[] = $arr[$i];
if (in_array($temp, $s)) {
$evenlyDistributedArray[] = [$arr[$i], $temp];
}
}
return $evenlyDistributedArray;
}
I'm trying to divide arrays equally from two sets of arrays
For example:
$arr1 = [a,b,c,d,e];
$arr2 = [1,2,3,4,5,6,7,8,9,10,11,12,13];
What I have tried:
$arr1 = [a,b,c,d,e];
$arr2 = [1,2,3,4,5,6,7,8,9,10,11,12,13];
$arrRes = [];
$key = 0;
for($i=0;$i<count($arr1);$i++){
$arrRes[$arr1[$key]][] = $arr2[$i];
$key++;
}
$key2 = 0;
for($k=0;$k<count($arr1);$k++){
$arrRes[$arr1[$key2]][] = $arr2[$key];
$key++;
$key2++;
if ($key == count($arr2)) {
break;
}
}
I expect to get the output:
[
"a" => [1,6,11],
"b" => [2,7,12],
"c" => [3,8,13],
"d" => [4,9],
"e" => [5,10]
]
but the actual output I get is :
[
"a" => [1,6],
"b" => [2,7],
"c" => [3,8],
"d" => [4,9],
"e" => [5,10]
]
Another way with just using 1 loop (comments in code)...
$arr1 = ['a','b','c','d','e'];
$arr2 = [1,2,3,4,5,6,7,8,9,10,11,12,13];
// Create output array from the keys in $arr1 and an empty array
$arrRes = array_fill_keys($arr1, []);
$outElements = count($arr1);
// Loop over numbers
foreach ( $arr2 as $item => $value ) {
// Add the value to the index based on the current
// index and the corresponding array in $arr1.
// Using $item%$outElements rolls the index over
$arrRes[$arr1[$item%$outElements]][] = $value;
}
print_r($arrRes);
Output...
Array
(
[a] => Array
(
[0] => 1
[1] => 6
[2] => 11
)
[b] => Array
(
[0] => 2
[1] => 7
[2] => 12
)
[c] => Array
(
[0] => 3
[1] => 8
[2] => 13
)
[d] => Array
(
[0] => 4
[1] => 9
)
[e] => Array
(
[0] => 5
[1] => 10
)
)
The code snippet bellow does exactly what you want. It calculates the max length of the resulting inner arrays (which in your case is 13/5+1=3) by dividing the length of the 2nd array with the length of the 1st array. Then, for each element in the 1st array, it goes from 0 to the max length and adds the element from the 2nd array at that position to the resulting array. In the case that the position is out of bounds, the inner for loop is exited.
$arr1 = ['a', 'b', 'c', 'd', 'e'];
$arr2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
$arrRes = [];
// create an empty result array of arrays
foreach($arr1 as $key){
// the keys are the values from the 1st array
$arrRes[$key] = [];
}
$maxLength = intval(count($arr2) / count($arr1)) + 1;
for($i = 0; $i < count($arr1); ++$i) {
for($j = 0; $j < $maxLength; ++$j) {
$pos = $j * count($arr1) + $i;
if($pos >= count($arr2)) {
break;
}
$arrRes[$arr1[$i]][] = $arr2[$pos];
}
}
The above code produces:
[
"a" => [1,6,11],
"b" => [2,7,12],
"c" => [3,8,13],
"d" => [4,9],
"e" => [5,10]
]
And if you want a result like this:
[
"a" => [1,2,3],
"b" => [4,5,6],
"c" => [7,8,9],
"d" => [10,11],
"e" => [12,13]
]
... then this code will do this (the main difference is in getting the position and determining when to break the inner loop):
$arr1 = ['a', 'b', 'c', 'd', 'e'];
$arr2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
$arrRes = [];
foreach($arr1 as $key){
$arrRes[$key] = [];
}
$maxLength = intval(count($arr2) / count($arr1)) + 1;
$pos = 0;
for($i = 0; $i < count($arr1); ++$i) {
$arraysLeftAfter = count($arr1) - $i - 1;
for($j = 0; $j < $maxLength && $pos < count($arr2); ++$j) {
if($arraysLeftAfter > 0) {
$elCountAfter = count($arr2) - $pos - 1;
$myLengthAfter = ($j + 1);
$maxLengthAfter = floor(($elCountAfter / $arraysLeftAfter) + 1);
if($myLengthAfter > $maxLengthAfter) {
break;
}
}
$arrRes[$arr1[$i]][] = $arr2[$pos++];
}
}
A different approach:
$arr1 = ['a','b','c','d','e'];
$arr2 = [1,2,3,4,5,6,7,8,9,10,11,12,13];
$i =0;
$res = array_fill_keys($arr1, []);
while(isset($arr2[$i])){
foreach($res as $k=>&$v){
if(!isset($arr2[$i])) break;
$v[] = $arr2[$i];
$i++;
}
}
print_r($res);
Result:
Array
(
[a] => Array
(
[0] => 1
[1] => 6
[2] => 11
)
[b] => Array
(
[0] => 2
[1] => 7
[2] => 12
)
[c] => Array
(
[0] => 3
[1] => 8
[2] => 13
)
[d] => Array
(
[0] => 4
[1] => 9
)
[e] => Array
(
[0] => 5
[1] => 10
)
)
This question already has answers here:
How to Sum Columns of a Multi-Dimensional Array?
(4 answers)
Closed 5 months ago.
I have an arrays with dynamic name. My array could be more than 3, depends and array variable should be unique
$loopThrice = 3;
$getSum = 0;
$total = array();
$array0 = array(5, 10, 15, 20, 25, 30);
$array1 = array(1, 2, 3, 4, 5, 6);
$array2 = array(2, 6, 8, 10, 12, 14);
for($a=0; $a < $loopThrice; $a++){ // loop 3x to get unique array name
foreach (${'array'.$a} as $key => $value) { // $array0, $array1, $array2,
//Right here is my problem, I'm not sure if this the correct way to get the sum of $array0,1,2
//get the sum of array0,1,2 -- newarray(8, 18, 26, 34, 42, 50)
$getSum +=
//store newarray
array_push($total, $getSum);
}
}
I need to get an output like this:
Array (
[0] => 8
[1] => 18
[2] => 26
[3] => 34
[4] => 43
[5] => 50
)
Why aren't you using a multidimensional array?
$array = array(); // hungarian notation
$array[] = array(5, 10, 15, 20, 25, 30);
$array[] = array(1, 2, 3, 4, 5, 6);
$array[] = array(2, 6, 8, 10, 12, 14);
In this case you will have an array of arrays:
Array
(
[0] => Array
(
[0] => 5
[1] => 10
[2] => 15
[3] => 20
[4] => 25
[5] => 30
)
[1] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)
[2] => Array
(
[0] => 2
[1] => 6
[2] => 8
[3] => 10
[4] => 12
[5] => 14
)
)
You can go with nested for loops:
$sumArray = array();
$arrayCount = count($array);
$elementCount = 0;
foreach($array as $subarray)
{
$count = count($subarray);
$elementCount = $elementCount < $count ? $count : $elementCount;
}
for($i = 0; $i < $elementCount; $i++)
{
$sumArray[$i] = 0;
for($j = 0; $j < $arrayCount; $j++)
{
$sumArray[$i] += $array[$j][$i];
}
}
print_r($sumArray);
The output is
Array
(
[0] => 8
[1] => 18
[2] => 26
[3] => 34
[4] => 42
[5] => 50
)
Now, if you have a disproportioned sub-arrays (i.e. different count of elements in each sub-array), you will still get some sort of result, as missing elements will be assumed to be 0. So, with the input of:
$array = array(); // hungarian notation
$array[] = array(5, 10, 15, 20, 25);
$array[] = array(1, 2, 3, 4, 5, 6);
$array[] = array(2, 6, 8, 10);
You will still get the result:
Array
(
[0] => 8
[1] => 18
[2] => 26
[3] => 34
[4] => 30
[5] => 6
)
Well the multi array is the way to go, but you can still do it this way:
$loopThrice = 3;
$getSum = 0;
$total = array();
$array0 = array(5, 10, 15, 20, 25, 30);
$array1 = array(1, 2, 3, 4, 5, 6);
$array2 = array(2, 6, 8, 10, 12, 14);
// find which arrray has the most values
for($a=0; $a < $loopThrice; $a++){
$max_index = (count(${'array'.$a}) > $max_index ? count(${'array'.$a}) : $max_index);
}
for($i=0; $i < $max_index; $i++){
for($a=0; $a < $loopThrice; $a++){
$total[$i] += ${'array'.$a}[$i];
}
}
print_r($total);
// prints Array ( [0] => 8 [1] => 18 [2] => 26 [3] => 34 [4] => 42 [5] => 50 )
This should work for you:
$array0 = array(5, 10, 15, 20, 25, 30);
$array1 = array(1, 2, 3, 4, 5, 6);
$array2 = array(2, 6, 8, 10, 12, 14);
$var_prefix = 'array';
$arr_count = 0;
$max_fields = 0;
while(isset(${$var_prefix.$arr_count})) {
$data[] = ${$var_prefix.$arr_count};
if(count(${$var_prefix.$arr_count})>$max_fields) {
$max_fields = count(${$var_prefix.$arr_count});
};
$arr_count++;
}
for($i=0; $i<$max_fields; $i++) {
$result[$i] = array_sum(array_column($data, $i));
}
echo '<pre>';
print_r($result);
echo '</pre>';
die();
I don't know why you have individual array variables, but the process remains the same as if you declare a single array containing those arrays as rows in a multi-dimensional array.
Once you have a multi-dimensional array, the spread operator (...) will feed columns of data into array_map()'s custom function body -- where array_sum() can be called upon.
This task is effectively summing transposed data.
Code: (Demo)
var_export(
array_map(fn() => array_sum(func_get_args()), $array0, $array1, $array2)
);
Or:
var_export(
array_map(fn(...$cols) => array_sum($cols), $array0, $array1, $array2)
);
Output (from either approach):
array (
0 => 8,
1 => 18,
2 => 26,
3 => 34,
4 => 42,
5 => 50,
)
I want a user defined function for sorting a multi dimension array:
<?php
$arr1 = array(
49,
8,
array(
'Muazam',
'Ali',
'Rana',
'Amina',
'Surya',
'Danish',
'Raina',
4,
3,
2,
1,
) ,
7,
6,
5,
4,
3,
2,
1,
0,
);
function abc($arr)
{
$len = count($arr) - 2;
foreach($arr as $key => $value)
{
for ($a = 0; $a <= $len; $a++)
{
if ($arr[$a] > $arr[$a + 1])
{
$temp4 = $arr[$a];
$arr[$a] = $arr[$a + 1];
$arr[$a + 1] = $temp4;
}
}
if (is_array($value))
{
abc($value, $a = $a + 1);
}
}
} //2nd foreach close
echo "<pre>";
print_r($arr);
echo "</pre>";
}
This is a basic usage of a recursive function:
$arr1 = array(49, 8, array(
'Muazam', 'Ali', 'Rana', 'Amina', 'Surya', 'Danish', 'Raina', 4, 3, 2, 1,
), 7, 6, 5, 4, 3, 2, 1, 0);
function recursiveSort(&$array)
{
foreach ($array as &$value) {
if (is_array($value)) {
recursiveSort($value);
}
}
return sort($array);
}
recursiveSort($arr1);
echo '<pre>';
print_r($arr1);
echo '</pre>';
The result would be:
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 4
[5] => 5
[6] => 6
[7] => 7
[8] => 8
[9] => 49
[10] => Array
(
[0] => Ali
[1] => Amina
[2] => Danish
[3] => Muazam
[4] => Raina
[5] => Rana
[6] => Surya
[7] => 1
[8] => 2
[9] => 3
[10] => 4
)
)
Here Is Answer.. Sorting a multi dimensional array without using built in function.
$arr1 = array(1,3,5,'2',array(99,55,array(111,444,array('a','r','p','e','t'),777),66,99),8,9,0,3,1);
function abc(&$arr)
{
$len=count($arr)-2;
foreach($arr as $key => &$value)
{
for ($a=0;$a<=$len;$a++){
if($arr[$a]>$arr[$a+1])
{
$temp4=$arr[$a];
$arr[$a]=$arr[$a+1];
$arr[$a+1]=$temp4;
}
}
if(is_array($value))
{
abc($value,$a=$a+1);
}
}//foreach close
//}//2nd foreach close
echo "<pre>";
return $arr;
echo "</pre>";
}//function close
print_r (abc($arr1));
I am using PHP and I have array from query
Array
(
[0] => stdClass Object
(
[question_id] => 13
[is_break] => 0
)
[1] => stdClass Object
(
[question_id] => 14
[is_break] => 1
)
[2] => stdClass Object
(
[question_id] => 15
[is_break] => 0
)
[3] => stdClass Object
(
[question_id] => 16
[is_break] => 1
)
[4] => stdClass Object
(
[question_id] => 17
[is_break] => 1
)
)
How to split (grouping) by is_break = 1 so i have question_id (13,14)(15,16)(17)
A simple and naive solution might look something like this:
var original = /* your original array, the one you posted */;
var result = [];
var tmp = [];
$.each(original, function(idx, obj) {
tmp.push(obj.question_id);
if(obj.is_break == 1) {
result.push(tmp);
tmp = [];
}
});
console.log(result); // returns array of array
HTH
EDIT: In PHP, it may look something like this (I am not too well-versed in PHP):
var $original = /* your original array, the one you posted */;
var $result = [];
var $tmp = [];
foreach($original as $obj) {
$tmp.push($obj.question_id); /* or could be $obj['question_id'] */
if($obj.is_break == 1) { /* or could be $obj['is_break'] */
$result.push($tmp);
$tmp = [];
}
});
Here's solution
$data = {your data};
$result = array();
$i = 0;
foreach($data as $k => $item) {
if ($item->is_break) {
$result[] = array_slice($data, $i, $k);
}
$i = $k;
}
print_r($result);
Try this:
<?php
$inputArr = Array
(
Array("question_id" => 13, "is_break" => 0),
Array("question_id" => 14, "is_break" => 1),
Array("question_id" => 15, "is_break" => 0),
Array("question_id" => 16, "is_break" => 1),
Array("question_id" => 17, "is_break" => 1)
);
$result = array();
$tmp = array();
foreach ($inputArr as $obj) {
//$tmp . push($obj . question_id); /* or could be $obj['question_id'] */
array_push($tmp, $obj['question_id']);
if ($obj['is_break'] == 1) { /* or could be $obj['is_break'] */
//$result . push($tmp);
array_push($result, $tmp);
$tmp = array();
}
}
var_dump($result);
?>
Thanks