Pyh.conf’25: a new PHP conference for the Russian-speaking community

Voting

: max(one, three)?
(Example: nine)

The Note You're Voting On

DavidG
15 years ago
A nice way to do sorting of a key on a multi-dimensional array without having to know what keys you have in the array first:

<?php
$people
= array(
array(
"name"=>"Bob","age"=>8,"colour"=>"red"),
array(
"name"=>"Greg","age"=>12,"colour"=>"blue"),
array(
"name"=>"Andy","age"=>5,"colour"=>"purple"));

var_dump($people);

$sortArray = array();

foreach(
$people as $person){
foreach(
$person as $key=>$value){
if(!isset(
$sortArray[$key])){
$sortArray[$key] = array();
}
$sortArray[$key][] = $value;
}
}

$orderby = "name"; //change this to whatever key you want from the array

array_multisort($sortArray[$orderby],SORT_DESC,$people);

var_dump($people);
?>

Output from first var_dump:

[0]=&gt;
array(3) {
["name"]=&gt;
string(3) "Bob"
["age"]=&gt;
int(8)
["colour"]=&gt;
string(3) "red"
}
[1]=&gt;
array(3) {
["name"]=&gt;

string(4) "Greg"
["age"]=&gt;
int(12)
["colour"]=&gt;
string(4) "blue"
}
[2]=&gt;
array(3) {
["name"]=&gt;
string(4) "Andy"
["age"]=&gt;
int(5)
["colour"]=&gt;

string(6) "purple"
}
}

Output from 2nd var_dump:

array(3) {
[0]=&gt;
array(3) {
["name"]=&gt;
string(4) "Greg"
["age"]=&gt;
int(12)
["colour"]=&gt;
string(4) "blue"
}
[1]=&gt;
array(3) {
["name"]=&gt;

string(3) "Bob"
["age"]=&gt;
int(8)
["colour"]=&gt;
string(3) "red"
}
[2]=&gt;
array(3) {
["name"]=&gt;
string(4) "Andy"
["age"]=&gt;
int(5)
["colour"]=&gt;

string(6) "purple"
}

There's no checking on whether your array keys exist, or the array data you are searching on is actually there, but easy enough to add.

<< Back to user notes page

To Top