Created
March 23, 2022 14:48
-
-
Save DarkcoderSe/8f936f949a5b7bfb6e86ebeec287efaa to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$arrayOfObjects = [ | |
[ | |
'id' => 10, | |
'name' => 'John', | |
'age' => 20 | |
], | |
[ | |
'id' => 2, | |
'name' => 'Jane', | |
'age' => 21 | |
], | |
[ | |
'id' => 3, | |
'name' => 'Jack', | |
'age' => 22 | |
], | |
[ | |
'id' => 4, | |
'name' => 'Kashif', | |
'age' => 26 | |
] | |
]; | |
function sortArrayOfObjects($sort = 'DESC') : void { | |
global $arrayOfObjects; | |
usort($arrayOfObjects, function($a, $b) use ($sort) | |
{ | |
return $sort == 'DESC' ? ($a['age'] < $b['age']) : ($a['age'] > $b['age']); | |
}); | |
} | |
function getObjectsAge() { | |
global $arrayOfObjects; | |
sortArrayOfObjects('ASC'); | |
$result = array_map(function($item){ | |
return $item['age']; | |
}, $arrayOfObjects); | |
return $result; | |
} | |
function convertObjectsToArray() | |
{ | |
global $arrayOfObjects; | |
$keys = getObjectsAge(); | |
$result = array(); | |
foreach ($arrayOfObjects as $key => $item) | |
{ | |
$result[$keys[$key]] = $item; | |
} | |
return $result; | |
} | |
sortArrayOfObjects('DESC'); | |
$result = convertObjectsToArray(); | |
print_r($result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment