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
• 551
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)

• over 5 years ago

OR
OR
Register

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

• Hire
• Post Projects

### Post Projects

• All at 0 Cost ....
• Post Tech Job
• Select Best Bidder
• Track the Project
• Approve Work and Pay safely
• Browse Nerds
• Work
• Find Projects Find Projects
• UI Design and UX
• Software Engineering
View more...
View less...
• Marketing
• General
View more...
View less...
• Manage
• Company Company

### Manage Company

• All at 0 Cost ....
• Manage Company and Employee Profiles
• Company wide Employee Productivity Reports
• Knowledge Sharing and Collaboration Tools
• Get Sales Lead and Bid for Tech Projects
• Send Invoices and Receive Payment Safely
• Learn
• Nerd Digest Nerd Digest
• UI Design and UX
• Software Engineering
View more...
View less...
• Marketing
• General
View more...
View less...
• Tech Q & A Tech Q & A
• UI Design and UX
• Software Engineering
View more...
View less...
• Marketing
• General
View more...
View less...