Quantcast
Channel: Eureka! » PHP
Viewing all articles
Browse latest Browse all 16

PHP – Sort a multidimensional array by specific key

$
0
0

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]


Filed under: PHP Tagged: PHP

Viewing all articles
Browse latest Browse all 16

Trending Articles