php - create another multi dimensional array from an array -
suppose have array
$x= ('a'=>31, 'b'=>12, 'c'=>13, 'd'=>25, 'e'=>18, 'f'=>10);
i need generate array this
$newx = (0 => array('a'=>31 , 'b' =>1) , 1 => array('b'=>11 , 'c' =>13 , 'd'=>8) , 2 =>array('d'=>17 , 'e'=>15) , 3=>array('e'=>3,'f'=>10);
now in case each value of $newx
has = 32
, how work $x[a] = 31 , $x[b] = 12
first of have make sum quantity 32 keeping index same new array i.e
array(0=>array('a'=>31,'b'=>1) , 1=>array('b'=>11) )
the process should continue each value of $x.
while i'm pretty sure homework assignment , well, should provide code of own, @ least try to, found thing amusing went ahead , gave try. guess i'll downvoted , deserve it, here goes anyway.
what need is:
- loop through array,
- determine elements give 32 , store result in final array.
- subtract value of last element result corresponding element of working array
- shrink array next deleting first elements until first element of array you're still working equals last element last result returned.
- if last result < 32, quit.
with in mind, please try find solution first , don't copy-paste code? :)
<?php $x = array('a'=>31, 'b'=>12, 'c'=>13, 'd'=>25, 'e'=>18, 'f'=>10); $result = array(); function calc($towalk){ // walk through array until have gathered enough 32, return result array $result = array(); foreach($towalk $key => $value){ $count = array_sum($result); if($count >= 32){ // if have more 32, subtract overage last array element $last = array_pop(array_keys($result)); $result[$last] -= ($count - 32); return $result; } $result[$key] = $value; } return $result; } // logic match first element $last = 'a'; // loop long have array while(count($x) > 0){ /* make sure first element matches last element of found array if last 1 went -> c start @ c , not @ b */ $keys = array_keys($x); if($last == $keys[0]){ // sub-array $partial = calc($x); // determine last key used, it's our new starting point $last = array_pop(array_keys($partial)); $result[] = $partial; //subtract last (partial) value used corresponding key in working array $x[$last] -= $partial[$last]; if(array_sum($partial) < 32) break; } /* reduce array in size 1, dropping first element should our resulting first element not match returned $last element logic jump place again , cut off element */ $x = array_slice($x , 1 ); } print_r($result);
Comments
Post a Comment