Last active
September 17, 2018 14:57
-
-
Save sohelrana820/6229ecda419055f37da6e6b6ce213055 to your computer and use it in GitHub Desktop.
Array Chunk based on Key PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @author: Sohel Rana <me.sohelrana@gmail.com> | |
* @author URL: http://sohelrana.me | |
* @licence: MIT | |
* @link: https://blog.sohelrana.me/array-chunk-based-on-key-value-in-php/ | |
* | |
* This function is for divide/group/chunk an multidimensional array based on same key. | |
*/ | |
/** | |
* @param $data | |
* @param $groupByKey | |
* @return array | |
*/ | |
function arrayChunkByKeyValue($data, $groupByKey) | |
{ | |
$groupArray = []; | |
foreach ($data as $singleData) { | |
$groupArray[$singleData[$groupByKey]][] = $singleData; | |
} | |
return $groupArray; | |
} | |
$posts = [ | |
[ | |
'category' => 'php', | |
'post_id' => 100, | |
], | |
[ | |
'category' => 'html', | |
'post_id' => 101, | |
], | |
[ | |
'category' => 'php', | |
'post_id' => 102, | |
], | |
[ | |
'category' => 'js', | |
'post_id' => 103, | |
], | |
[ | |
'category' => 'html', | |
'post_id' => 104, | |
], | |
[ | |
'category' => 'php', | |
'post_id' => 104, | |
], | |
]; | |
$result = arrayChunkByKeyValue($posts, 'category'); | |
var_export($result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment