Skip to content

Instantly share code, notes, and snippets.

@sohelrana820
Last active September 17, 2018 14:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sohelrana820/6229ecda419055f37da6e6b6ce213055 to your computer and use it in GitHub Desktop.
Save sohelrana820/6229ecda419055f37da6e6b6ce213055 to your computer and use it in GitHub Desktop.
Array Chunk based on Key PHP
<?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