I have an array with two items, which are also arrays themselves: product
and countries
.
There are cases in which the countries
array is the same for more than one product, like basic
and pro
in the example below.
Given this array:
$array = [
[
'product' => [
'value' => 'basic',
'label' => 'Basic'
],
'countries' => [
'Japan', // these
'Korea' // two...
],
],
[
'product' => [
'value' => 'pro',
'label' => 'Pro'
],
'countries' => [
'Japan', // ...and these two
'Korea' // are identical...
],
],
[
'product' => [
'value' => 'expert',
'label' => 'Expert'
],
'countries' => [
'Japan',
'France'
],
]
];
I would like to create new arrays grouped by countries
, more precisely,
this is the result I'm after:
$array = [
[
'product' => [
[
'value' => 'basic',
'label' => 'Basic'
],
[
'value' => 'pro',
'label' => 'Pro'
]
],
'countries' => [
'Japan', // ...so they are now one single array
'Korea' // as the two products 'basic' and 'pro' have been grouped
],
],
[
'product' => [
'value' => 'expert',
'label' => 'Expert'
],
'countries' => [
'Japan',
'France'
],
]
];
As you can see in the second snippet, what I'm trying to do is to group basic
and pro
together in the same array, since they both share the exact same countries
(Korea
and Japan
).
I've been trying for days to play around with this code, but it only seems to work if product
and countries
are strings rather than arrays:
$grouped = array();
foreach ($array as $element) {
$grouped[$element['countries']][] = $element;
}
var_dump($grouped);
My Answer:
> 'basic',
> 'countries' = ['US', 'CA', 'MX']
> ],
> [
> 'product' = 'pro',
> 'countries' = ['US', 'CA', 'MX']
> ],
> [
> 'product' = 'premium',
> 'countries' = ['US', 'CA']
> ],
> [
> 'product' = 'standard',
> 'countries' = ['US']
> ]
>];__I want to group the rows of data by the countries array and create subsets with variable depth. In this case, the subsets would be:__1. US
> - basic
> - pro
> - premium
> - standard
>2. CA
> - basic
> - pro
> - premium
>3. MX
> - basic
> - pro__How can I achieve this in PHP?
Rate this post
4 of 5 based on 7691 votesComments