PHP – Sort a multidimensional array by specific key

Assume you have the following array in PHP.

$myArray = array(
  0 => array(
    'hashtag' => 'a7e87329b5eab8578f4f1098a152d6f4',
    'title'   => 'Flower',
    'order'   => 3
  ),
  1 => array(
    'hashtag' => 'b24ce0cd392a5b0b8dedc66c25213594',
    'title'   => 'Free',
    'order'   => 2
  ),
  2 => array(
    'hashtag' => 'e7d31fc0602fb2ede144d18cdffd816b',
    'title'   => 'Ready',
    'order'   => 1
  ),
);

 

You can simple sort it by the order key by implementing the following array_sort_by_column() function.

<?php

$myArray = array(
  0 => array(
    'hashtag' => 'a7e87329b5eab8578f4f1098a152d6f4',
    'title'   => 'Flower',
    'order'   => 3
  ),
  1 => array(
    'hashtag' => 'b24ce0cd392a5b0b8dedc66c25213594',
    'title'   => 'Free',
    'order'   => 2
  ),
  2 => array(
    'hashtag' => 'e7d31fc0602fb2ede144d18cdffd816b',
    'title'   => 'Ready',
    'order'   => 1
  ),
);

  array_sort_by_column($myArray, 'order');

  print '<pre>';
  print_r($myArray);
  print '</pre>';

  function array_sort_by_column(&$arr, $col, $dir = SORT_ASC) {
    $sort_col = array();
    foreach ($arr as $key=> $row) {
        $sort_col[$key] = $row[$col];
    }
    array_multisort($sort_col, $dir, $arr);
  }
?>

 

Done =)

Reference: StackOverflow – Sort multidimensional Array by Value (2) [duplicate]

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s