Answer the question
In order to leave comments, you need to log in
How to sort in PHP a multidimensional JSON array by the value of a certain key (in ascending order) and additionally alphabetically (by other key)?
Good afternoon!
Tell me, please, I can’t find (guess) a solution in any way .. How to sort (in PHP 5.6/7) a multidimensional JSON array by the value of a certain key (in ascending order) and additionally alphabetically (by other key)?
Let me explain. There is this array:
[{
"id": "26",
"strana": "Таиланд",
"otel_nazvanie": "Villa Danica",
"otel_kol_vo_zvezd": "3",
"otel_stoimost": "22900"
}, {
"id": "26",
"strana": "Греция",
"otel_nazvanie": "Vila Tufi",
"otel_kol_vo_zvezd": "3",
"otel_stoimost": "27700"
}, {
"id": "26",
"strana": "Кипр",
"otel_nazvanie": "Villa Kralj",
"otel_kol_vo_zvezd": "3",
"otel_stoimost": "28800"
}, {
"id": "26",
"strana": "Кипр",
"otel_nazvanie": "Rooms Rio",
"otel_kol_vo_zvezd": "3",
"otel_stoimost": "28750"
}, {
"id": "26",
"strana": "Таиланд",
"otel_nazvanie": "Obala Zelena",
"otel_kol_vo_zvezd": "3",
"otel_stoimost": "32050"
}, {
... // и так далее, до 100 штук.
}]
[{
"id": "26",
"strana": "Греция",
"otel_nazvanie": "Vila Tufi",
"otel_kol_vo_zvezd": "3",
"otel_stoimost": "27700"
}, {
"id": "26",
"strana": "Кипр",
"otel_nazvanie": "Rooms Rio",
"otel_kol_vo_zvezd": "3",
"otel_stoimost": "28750"
}, {
"id": "26",
"strana": "Таиланд",
"otel_nazvanie": "Villa Danica",
"otel_kol_vo_zvezd": "3",
"otel_stoimost": "22900"
}, {
... // и так далее.
}]
Answer the question
In order to leave comments, you need to log in
Why sort? Just go through the array once and select the desired data?
$a=json_decode($json, true);
$res=array();
foreach($a as $k=>$v){
if(!isset($res[$v['strana']])){
$res[$v['strana']]=$v['otel_stoimost'];
}else{
$res[$v['strana']]=min($res[$v['strana']], $v['otel_stoimost']);
}
}
print_r($res);
$a=json_decode($json, true);
$res=array();
foreach($a as $k=>$v){
if(!isset($res[$v['strana']])){
$res[$v['strana']]=$v;
}else{
if($v['otel_stoimost']<$res[$v['strana']]['otel_stoimost']){
$res[$v['strana']]=$v;
}
}
}
$min_prices=array();
foreach($res as $v){
$min_prices[]=$v;
}
echo json_encode($min_prices);
echo '<ul>';
foreach($res as $k=>$v){
echo '<li>'.$k.' от '.$v.' руб.</li>';
}
echo '</ul>';
++ You don't need to sort anything.
one pass
for(){
if(strana.otel_stoimost < min_strana.otel_stoimost)
{
min_strana.otel_stoimost = strana.otel_stoimost
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question