Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Decomposing the associative array in chunks based on their keys

    • 0
    • 1
    • 0
    • 2
    • 1
    • 0
    • 0
    • 0
    • 388
    Comment on it

    Consider you have two arrays like the below:

    1) $arr1 = Array ( [0] => 2 [1] => 2 [2] => 2 [3] => 3 [4] => 3 ) 2) $arr2 = Array ( [0] => 28 [1] => 48 [2] => 21 [3] => 160 [4] => 10 )

    You wants to make arr1 key for arr2, You can use phps standard array function i.e., array_combine like:

    array_combine($arr1, $arr2);

    It will result you:

    array ( [2] => 21 [3] => 10 )

    But some time you may need to combine the arrays that it always contains max value for a key for ex:

    array ( [2] => 48 [3] => 160 )

    Then you will be needed to write custom code:

    Function Call: $newArray = getNewArray($arr1, $arr2);

    Function Definition:

    public function getNewArray($arr1, $arr2) { $arrayChunks = array(); $arrayMaxChunks = array();

     //Split the array into chunks based on similiar keys
     foreach ($arr1 as $key => $value) {
         if($key==0)
           $arrayChunks[$arr1[0]][] = $arr2[0];
        else
           $arrayChunks[$arr1[$key]][0] = $arr2[$key];  
     }
    
     // Find the maximum in each smaller array chunks
     foreach ($arrayChunks as $key => $value) {
         $arrayMaxChunks[$key] = max($value);
     }
     return $arrayMaxChunks;
    

    }

    It will result you: array ( [2] => 48 [3] => 160 )

 1 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: