Created
January 11, 2018 00:06
-
-
Save gustavonovaes/db2151b063a9c85ef9c236b37879d9f7 to your computer and use it in GitHub Desktop.
This file contains 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 | |
$json = <<<'EOD' | |
[ | |
{ | |
"id": 1, | |
"name": "Sopa de castanha do par\u00e1", | |
"price": 9.82, | |
"specifications": [ | |
"low-carb" | |
] | |
}, | |
{ | |
"id": 2, | |
"name": "C\u00e1psulas de castanha do par\u00e1", | |
"price": 2.37, | |
"specifications": [ | |
"lactose-free", | |
"low-carb" | |
] | |
}, | |
{ | |
"id": 3, | |
"name": "Chips de milho", | |
"price": 7.24, | |
"specifications": [ | |
"low-carb", | |
"vegan", | |
"gluten-free", | |
"vegetarian", | |
"lactose-free" | |
] | |
} | |
] | |
EOD; | |
$products = json_decode($json, true); | |
function array_sort_numeric_column($array, $column, $asc = true) | |
{ | |
$index = $asc ? 0 : 1; | |
usort($array, function () use ($column, $index) { | |
$args = func_get_args(); | |
$a = $args[$index]; | |
$b = $args[abs($index - 1)]; | |
return $a[$column] == $b[$column] ? 1 : | |
$a[$column] < $b[$column] ? -1 : 1; | |
}); | |
return $array; | |
} | |
function custom_print($array) | |
{ | |
foreach ($array as $values) { | |
echo sprintf( | |
"%s - %s %s", | |
$values['id'], | |
$values['price'], | |
$values['name'] | |
) . PHP_EOL; | |
} | |
echo PHP_EOL; | |
} | |
custom_print(array_sort_numeric_column($products, 'price', true)); | |
custom_print(array_sort_numeric_column($products, 'price', false)); | |
custom_print(array_sort_numeric_column($products, 'id', true)); | |
custom_print(array_sort_numeric_column($products, 'id', false)); | |
/* | |
# Output | |
2 - 2.37 Cápsulas de castanha do pará | |
3 - 7.24 Chips de milho | |
1 - 9.82 Sopa de castanha do pará | |
1 - 9.82 Sopa de castanha do pará | |
3 - 7.24 Chips de milho | |
2 - 2.37 Cápsulas de castanha do pará | |
1 - 9.82 Sopa de castanha do pará | |
2 - 2.37 Cápsulas de castanha do pará | |
3 - 7.24 Chips de milho | |
3 - 7.24 Chips de milho | |
2 - 2.37 Cápsulas de castanha do pará | |
1 - 9.82 Sopa de castanha do pará | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment