John Davidson

Group multi array by key and value PHP

0 comments
Message:


I have an array like the one below


array:4 [▼
0 => array:3 [▼
0 => array:2 [▼
"url" => "https://domain.com.vn"
"value" => "Keyword B3"
]
1 => array:2 [▼
"url" => "https://domain.com.vn"
"value" => "[IMAGES 1]"
]
]
1 => array:3 [▼
0 => array:2 [▼
"url" => "https://domain-4.com.vn"
"value" => "D1"
]
1 => array:2 [▼
"url" => "https://domain-4.com.vn"
"value" => "E3"
]
]
]

I want to combine the above 2 arrays into 1 array as follows (number of items in 2 arrays is always equal):


$result = [
[
"url" => [
"https://domain.com.vn",
"https://domain-4.com.vn"
]
"value" => [
"Keyword B3",
"D1"
]
],
[
"url" => [
"https://domain.com.vn",
"https://domain-4.com.vn"
],
"value" => [
"[IMAGES 1]",
"E3"
]
]
]

I have searched a lot but have not found a solution yet. Thanks for any help.



My Answer:
> ["key" => "A", "value" => 1]
> 1 = ["key" => "B", "value" => 2]
> 2 = ["key" => "A", "value" => 3]
> 3 = ["key" => "B", "value" => 4]
]

To group this array by both the "key" and "value" fields, you can use the following PHP code:

php
$array = [
["key" => "A", "value" => 1],
["key" => "B", "value" => 2],
["key" => "A", "value" => 3],
["key" => "B", "value" => 4]
];

$groupedArray = [];

foreach ($array as $item) {
$groupedArray[$item['key']][$item['value']] = $item;
}

print_r($groupedArray);


This code will output the following grouped array:


Array
(
[A] => Array
(
[1] => Array
(
[key] => A
[value] => 1
)

[3] => Array
(
[key] => A
[value] => 3
)

)

[B] => Array
(
[2] => Array
(
[key] => B
[value] => 2
)

[4] => Array
(
[key] => B
[value] => 4
)

)

)


This code groups the original array by the "key" field first, and then by the "value" field within each group.

Rate this post

5 of 5 based on 5562 votes

Comments




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