Saturday, December 10, 2016

PHP Sort Multidimensional array with key value


<?php
$needSort = array(
    array("name" => "Bob", "age" => 8, "colour" => "red"),
    array("name" => "Greg", "age" => 12, "colour" => "blue"),
    array("name" => "Andy", "age" => 5, "colour" => "purple")
);
echo "<h3>Original Array</h3><pre>";
print_r($needSort);
echo "</pre>";

$orderBy = "name";
$sortArray = array();
$sortArray[$orderBy] = array();

foreach ($needSort as $obj) {
    $sortArray[$orderBy][] = $obj[$orderBy]; //Sort by name
}

array_multisort($sortArray[$orderBy], SORT_ASC, $needSort);

echo "<h3>Sorted Array</h3><pre>";
print_r($needSort);
echo "</pre>";
?>

Output



Original Array

Array
(
    [0] => Array
        (
            [name] => Bob
            [age] => 8
            [colour] => red
        )

    [1] => Array
        (
            [name] => Greg
            [age] => 12
            [colour] => blue
        )

    [2] => Array
        (
            [name] => Andy
            [age] => 5
            [colour] => purple
        )

)


Sorted Array

Array
(
    [0] => Array
        (
            [name] => Andy
            [age] => 5
            [colour] => purple
        )

    [1] => Array
        (
            [name] => Bob
            [age] => 8
            [colour] => red
        )

    [2] => Array
        (
            [name] => Greg
            [age] => 12
            [colour] => blue
        )

)

1 comment:

  1. Nice site....Please refer this site also Our vision success!Training are focused on perfect improvement of technical skills for Freshers and working professional. Our Training classes are sure to help the trainee with COMPLETE PRACTICAL TRAINING and Real time methodologies
    Asp.Net Training in Chennai | Dot Net Training Center in Chennai
    Software Testing Institutes in Chennai | Manual Testing Training in Chennai
    Java Training Institute in Chennai | Core Java Training in Chennai
    PHP training in chennai | Best PHP Training in chennai

    ReplyDelete