Arrays - markhowellsmead/helpers GitHub Wiki

Sort multidimensional array by subelement key

$team = array(
    [0] = array(
        'first_name' => 'Mark',
        'last_name' => 'Howells-Mead'
    ),
    [1] = array(
        'first_name' => 'Ansel',
        'last_name' => 'Adams'
    )
);

usort($team, function ($first, $second) {
    return (string) $first['last_name'] > (string) $second['last_name'];
});

// Result: array will be resorted alphabetically, with Adams in first place

Sort multidimensional array by second array

Requires PHP 7+ because of the spaceship operator.

$site_order = [1,3,4,2,5];

$sites = get_sites();

/*$sites = [
	{
		'blog_id' => 1,
		...
	},
	{
		'blog_id' => 2,
		...
	},
	{
		'blog_id' => 3,
		...
	},
	{
		'blog_id' => 4,
		...
	},
	{
		'blog_id' => 5,
		...
	},
];*/

usort($sites, function ($a, $b) use ($site_order) {
	$posA = array_search($a->blog_id, $site_order);
	$posB = array_search($b->blog_id, $site_order);
	return $posA <=> $posB;
});

var_dump($sites);