Reputation: 35
What would be the best way to group repeated values of an array like this:
$array = [
0 => ['id'=>1, 'name'=>'prod1', 'type'=>'a', 'price'=>2.50],
1 => ['id'=>1, 'name'=>'prod1', 'type'=>'b', 'price'=>5.50],
2 => ['id'=>1, 'name'=>'prod1', 'type'=>'c', 'price'=>10.50],
3 => ['id'=>2, 'name'=>'prod2', 'type'=>'a', 'price'=>3.50],
4 => ['id'=>2, 'name'=>'prod2', 'type'=>'b', 'price'=>7.50]
];
in order to get an output array like so:
$sorted_array = [
0 => ['id'=>1, 'name'=>'prod1', 'type'=>['a' => ['price'=>2.50],
'b'=> ['price'=>5.50],
'c'=> ['price'=>10.50]
]
],
1 => ['id'=>2, 'name'=>'prod2', 'type'=>['a'=>['price'=>3.50],
'b'=>['price'=>7.50]
]
]
];
Upvotes: 3
Views: 49
Reputation: 35
Zeke, I took your approach an changed it slightly because the compiler was complaining about some "Undefined offsets".
This is how it is now:
$sorted_array = [];
for($i = 0; $i < count($array); $i++){
if($i == 0){
$sorted_array[$i]['id'] = $array[$i]['id'];
$sorted_array[$i]['name'] = $array[$i]['name'];
$sorted_array[$i]['type'][$array[$i]['type']]['price'] = $array[$i]['price'];
}else{
$last = end($sorted_array);
$key = key($sorted_array);
if($last['id']==$array[$i]['id']){
$sorted_array[$key]['type'][$array[$i]['type']]['price'] = $array[$i]['price'];
}else{
$k = $key+1;
$sorted_array[$k]['id'] = $array[$i]['id'];
$sorted_array[$k]['name'] = $array[$i]['name'];
$sorted_array[$k]['type'][$array[$i]['type']]['price'] = $array[$i]['price'];
}
}
}
Output:
Array
(
[0] => Array
(
[id] => 1
[name] => prod1
[type] => Array
(
[a] => Array
(
[price] => 2.5
)
[b] => Array
(
[price] => 5.5
)
[c] => Array
(
[price] => 10.5
)
)
)
[1] => Array
(
[id] => 2
[name] => prod2
[type] => Array
(
[a] => Array
(
[price] => 3.5
)
[b] => Array
(
[price] => 7.5
)
)
)
)
Thanks a million Zeke, your answer helped me a lot.
Upvotes: 0
Reputation: 1291
This is not exactly the best way to do it, but it does what you want:
$sorted_array = [];
for($i = 0; $i < count($array); $i++){
$k = $array[$i]['id']-1;
if($sorted_array[$k] == null){
$sorted_array[$k]['id'] = $array[$i]['id'];
$sorted_array[$k]['name'] = $array[$i]['name'];
}
$sorted_array[$k]['type'][$array[$i]['type']]['price'] = $array[$i]['price'];
}
I tried it out on a local server using your array and got this:
Array
(
[0] => Array
(
[id] => 1
[name] => prod1
[type] => Array
(
[a] => Array
(
[price] => 2.5
)
[b] => Array
(
[price] => 5.5
)
[c] => Array
(
[price] => 10.5
)
)
)
[1] => Array
(
[id] => 2
[name] => prod2
[type] => Array
(
[a] => Array
(
[price] => 3.5
)
[b] => Array
(
[price] => 7.5
)
)
)
)
Upvotes: 1