Categories
Code Area PHP Programming Tips and Tricks Tools and Technologies

Array Chunk based on Key Value in PHP

Sometimes programmer needs to chunk or grouping array based on the array key value. Look at the below code snippet, here I have a multidimensional array, and I want to group all same elements of each category.

OUTPUT:

array (
  'php' => 
  array (
    0 => 
    array (
      'category' => 'php',
      'post_id' => 100,
    ),
    1 => 
    array (
      'category' => 'php',
      'post_id' => 102,
    ),
    2 => 
    array (
      'category' => 'php',
      'post_id' => 104,
    ),
  ),
  'html' => 
  array (
    0 => 
    array (
      'category' => 'html',
      'post_id' => 101,
    ),
    1 => 
    array (
      'category' => 'html',
      'post_id' => 104,
    ),
  ),
  'js' => 
  array (
    0 => 
    array (
      'category' => 'js',
      'post_id' => 103,
    ),
  ),
)

By Sohel Rana

PHP Programmer, Software Engineer & Technology lover

Leave a Reply

Your email address will not be published. Required fields are marked *