I’m using PHP, and I have the following array and have been trying to figure out how I can flatten it in the following manner. This is an array that is created from a JSON by using json_decode, and the end result will be another json file.
So wherever we have a unique name, the patternType and type will always be the same in every element of the parent array. I need a way to basically "collapse" the array and combine the array’s while adding new element to the action array.
Current Data Structure.
Array
(
[abc] => Array
[0] => Array
(
[foo] => *
[action] => Read
[resource] => Array
(
[name] => name_1
[patternType] => fixed
[type] => partition
)
)
[1] => Array
(
[foo] => *
[action] => Write
[resource] => Array
(
[name] => name_1
[patternType] => fixed
[type] => partition
)
)
[2] => Array
(
[foo] => *
[action] => Read
[resource] => Array
(
[name] => name_2
[patternType] => fixed
[type] => partition
)
)
[3] => Array
(
[foo] => *
[action] => Alter
[resource] => Array
(
[name] => name_2
[patternType] => fixed
[type] => partition
)
)
)
Needed Data Structure
Array
(
[abc] => Array
[0] => Array
(
[foo] => *
[action] => Array
(
[0] => Read
[1] => Write
)
[resource] => Array
(
[name] => name_1
[patternType] => fixed
[type] => partition
)
)
[1] => Array
(
[foo] => *
[action] => Array
(
[0] => Read
[1] => Alter
)
[resource] => Array
(
[name] => name_2
[patternType] => fixed
[type] => partition
)
)
)
I’ve tried various functions like array_merges, array_merge_recursive, etc… I also tried looping through the array, and creating a secondary array and creating the data structure properly there, but i always have the problem of figuring out how to reference the parent arrays in that case, b/c the order of the child arrays can always differ.
2
Answers
here is the solution for you
To achieve the desired data structure, you can loop through the original array and use a temporary associative array to group the elements by the "name" field. You can then create the desired structure from this temporary array. Here is a PHP code example to do that:
This will give you the desired data structure in the
$outputArray
.