Skip to content

Instantly share code, notes, and snippets.

@attackant
Last active August 29, 2015 13:56
Show Gist options
  • Save attackant/9117413 to your computer and use it in GitHub Desktop.
Save attackant/9117413 to your computer and use it in GitHub Desktop.
Sort an associative PHP array by HTML content, keeping array indexes (also sort one array by another)
<?php
// sort a multidimensional array by value, stripping HTML, keeping array indexes, sorting by the contents of original HTML putting the HTML back
$options = array(
1001 => "<a href='?post=590&amp;action=edit'>James Whistler</a>",
1004 => '<a href="106">Francisco Toledo</a>',
1002 => '<a href="103">Franco Marzilli</a>',
1000 => '<a href="100">John Bashor</a>',
1003 => '<a href="105">Daniel LaRue Johnson</a>',
1006 => '<a href="108">Ray Kass</a>',
1005 => '<a href="107">Jim Huntington</a>',
1007 => '<a href="104">Charles Arnoldi</a>',
'null' => '',
);
$options_sorted = array();
foreach($options as $k => $v) {
$v = strip_tags($v);
$options_sorted[$k] = $v;
}
asort($options_sorted);
function sort_by_array($a, $b) {
global $options_sorted;
return $options_sorted[$a] < $options_sorted[$b] ? -1 : 1;
}
uksort($options, 'sort_by_array');
var_dump($options);
var_dump($options_sorted);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment