PHP sort array alphabetically using a subarray value


For simple php,

<?php
$a = Array(
  0 => Array(
         "0" => 1,
         "1" => A,

    ),
    1 => Array(
        "0" => 2,
		"1" => B,		
    ),  
    2 => Array(
       "0" => 2,
		"1" => Z,
    ),
	3 => Array
	(
		"0" => 3,
		"1" => C,		
	),
	4 => Array
	(
		"0" => 4,
		"1" => D,		
	),
);
function compareByName($a, $b) {
  return strcmp($a[1], $b[1]);
}
usort($a, 'compareByName');
print_r($a);

———————————————————-
For oop,

<?php
class SortArray{
	function setArray(){
		usort($a,function($a, $b){
			return strcmp($a[1], $b[1]);
		});
		print_r($a);
	}
}
?>

==============================
Output :
==============================

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => A
        )

    [1] => Array
        (
            [0] => 2
            [1] => B
        )

    [2] => Array
        (
            [0] => 3
            [1] => C
        )

    [3] => Array
        (
            [0] => 4
            [1] => D
        )

    [4] => Array
        (
            [0] => 2
            [1] => Z
        )

)
Advertisements
Posted in php

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 )

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s