John Davidson

php - How to transform array of arrays into grouped arrays containing key and values?

0 comments
Message:


Following is the input array:


$input = [
[
'id' => 96,
'shipping_no' => 212755-1,
'part_no' => 'reterty',
'description' => 'tyrfyt',
'packaging_type' => 'PC'
],
[
'id' => 96,
'shipping_no' => 212755-1,
'part_no' => 'dftgtryh',
'description' => 'dfhgfyh',
'packaging_type' => 'PC'
],
[
'id' => 97,
'shipping_no' => 212755-2,
'part_no' => 'ZeoDark',
'description' => 's%c%s%c%s',
'packaging_type' => 'PC'
]
];

I want the above to be transformed into like this:


$output = [
[
'key' => 96,
'value' => [
[
'shipping_no' => 212755-1,
'part_no' => 'reterty',
'description' => 'tyrfyt',
'packaging_type' => 'PC'
],
[
'shipping_no' => 212755-1,
'part_no' => 'dftgtryh',
'description' => 'dfhgfyh',
'packaging_type' => 'PC'
]
]
],
[
'key' => 97,
'value' => [
[
'shipping_no' => 212755-2,
'part_no' => 'ZeoDark',
'description' => 's%c%s%c%s',
'packaging_type' => 'PC'
]
]
]
];

I have tried to implement it like this:


$result = [];
foreach ($input as $value) {
$result[] = ['key' => $value['id'], 'value' => ['shipping_no' => $value['shipping_no'], 'part_no' => $value['part_no'], 'description' => $value['description'], 'packaging_type' => $value['packaging_type']]];
}

It is not getting grouped based on common key. Please help me with the possible approach that I should take to solve this.



My Answer:
You can achieve the desired transformation by first grouping the input array based on the 'id' key and then creating the output array structure. Here's how you can do it:

php
$input = [
[
'id' => 96,
'shipping_no' => '212755-1',
'part_no' => 'reterty',
'description' => 'tyrfyt',
'packaging_type' => 'PC'
],
[
'id' => 96,
'shipping_no' => '212755-1',
'part_no' => 'dftgtryh',
'description' => 'dfhgfyh',
'packaging_type' => 'PC'
],
[
'id' => 97,
'shipping_no' => '212755-2',
'part_no' => 'ZeoDark',
'description' => 's%c%s%c%s',
'packaging_type' => 'PC'
]
];

// Group the input array based on the 'id' key
$grouped = [];
foreach ($input as $value) {
$grouped[$value['id']][] = $value;
}

// Create the output array structure
$output = [];
foreach ($grouped as $key => $values) {
$output[] = ['key' => $key, 'value' => $values];
}

print_r($output);


This code will output the desired transformed array structure as shown in the `$output` variable.

Rate this post

3 of 5 based on 8701 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us