Reputation: 45
I want to rearrange a array by these key values. let me explain. Please check my array values
Array
(
[0] => stdClass Object
(
[user_id] => 103
[recipe_id] => 90
)
[1] => stdClass Object
(
[user_id] => 103
[recipe_id] => 90
)
[2] => stdClass Object
(
[user_id] => 103
[recipe_id] => 64
)
[3] => stdClass Object
(
[user_id] => 103
[recipe_id] => 90
)
[4] => stdClass Object
(
[user_id] => 103
[recipe_id] => 64
)
)
This is my array result and I want it rearrange by key recipe_id. which recipe_id is same they will come together. like that
Array
(
[0] => stdClass Object
(
[user_id] => 103
[recipe_id] => 90
)
[1] => stdClass Object
(
[user_id] => 103
[recipe_id] => 90
)
[2] => stdClass Object
(
[user_id] => 103
[recipe_id] => 90
)
[3] => stdClass Object
(
[user_id] => 103
[recipe_id] => 64
)
[4] => stdClass Object
(
[user_id] => 103
[recipe_id] => 64
)
)
How can i arrange this array values??. I want to show array result like I show above example. is there any way to rearrange my array with same key value.
Thanks in advance
Upvotes: 0
Views: 106
Reputation: 424
First convert object to array form
json_decode(json_encode(json_decode($arr_value_list)), true);
// $arr_value_list is values array
Then use following function to sort values
$key_name = 'user_id';
usort($arr_value_list, function ($a, $b) use(&$key_name)
{
return $a[$name] - $b[$name];
});
Get Output by print_r($arr_value_list);
Upvotes: 0
Reputation: 1204
try this
$sorted = collect($array)
->sortByDesc('recipe_id')
->values()
->all();
if you want to divide them by recipe_id you can use
$grouped = collect($array)
->groupBy('recipe_id')
->toArray();
Upvotes: 3
Reputation: 456
You can use php usort function as follow.
$my_sort = function ($a , $b) {
if ($a->user_id == $b->user_id) {
if($a->recipe_id == $b->recipe_id) {
return 0;
}
return ($a->recipe_id < $b->recipe_id) ? -1 : 1;
}
return ($a->user_id < $b->user_id) ? -1 : 1;
};
$result = usort($arr,$my_sort);
Upvotes: 0