Skip to content

Commit

Permalink
add array sorting
Browse files Browse the repository at this point in the history
  • Loading branch information
nrenvoise-ubitransport committed May 11, 2021
1 parent 5eee7fb commit 4b07c03
Showing 1 changed file with 64 additions and 0 deletions.
64 changes: 64 additions & 0 deletions array/order_array.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?php

function sortArrayBy(array &$items, array $order, string $property)
{
usort($items, function ($a, $b) use ($order, $property) {
$weightA = $a[$property];
$weightB = $b[$property];

return $order[$weightA] - $order[$weightB];
});
}

function printArray(array $items) {
foreach ($items as $item) {
echo json_encode($item)."\n";
}
}

$basket = [
[
'fruit' => 'raspberry',
'color' => 'red',
],
[
'fruit' => 'apple',
'color' => 'yellow',
],
[
'fruit' => 'pear',
'color' => 'green',
],
[
'fruit' => 'peach',
'color' => 'purple',
]
];

echo "sort by name:\n";

sortArrayBy(
$basket,
[
'apple' => 1,
'peach' => 2,
'pear' => 3,
'raspberry' => 4
],
'fruit'
);
printArray($basket);

echo "sort by color:\n";

sortArrayBy(
$basket,
[
'green' => 1,
'yellow' => 2,
'purple' => 3,
'red' => 4
],
'color'
);
printArray($basket);

0 comments on commit 4b07c03

Please sign in to comment.