I want to sort a php associative array according to price in case of token
and yearly price in case of subscription
plan
Here is the exmaple:
$packs = [
[
'name' => 'starter',
'type' => 'token',
'price' => 199
],
[
'name' => 'business',
'type' => 'subscription',
'price' => [
'monthly' => 19,
'yearly' => 219,
]
],
[
'name' => 'professional',
'type' => 'subscription',
'price' => [
'monthly' => 9,
'yearly' => 119,
]
],
]
I want to get a result like this
[
[
'name' => 'professional',
'type' => 'subscription',
'price' => [
'monthly' => 9,
'yearly' => 119,
]
],
[
'name' => 'starter',
'type' => 'token',
'price' => 199
],
[
'name' => 'business',
'type' => 'subscription',
'price' => [
'monthly' => 19,
'yearly' => 219,
]
],
]
I tried this kind of solution but it returned an array with price in the key, but don’t need price as key
$price = [];
foreach( $packs as $key => $value ){
if( $value['type'] == 'token' ){
$price[intval($value['price'])] = $value;
}
if( $value['type'] == 'subscription' ){
$price[intval($value['price']['yearly'])] = $value;
}
}
krsort( $price );
$new_packs = [];
foreach($price as $k => $value){
$new_packs[] = $k;
}
//print_r($new_packs) // it returned same as the given array
2
Answers
but it returned an array with price in the key, but don’t need price as key Ok, but you are literally doing it in
$price[intval($value['price'])] =
and likewise.Don’t use
krsort
. Useksort
(Since you want the ordering in ascending order)Also, you just have to use
$value
instead of$k
to take only the array values like below, becausekey => value
is the syntax for foreach and here$k
is your key and$value
is your value.OR
A better alternative is to simply use
array_values
like below: