php - How to merge array by key values which are repeating
Get the solution ↓↓↓I have an array like this what i want is to sub array converts into unique key sub array with multiple unique keys. I have tried array_merge_recursive function which is not working because i have multiple arrays in loop and the function works with 2 or 3 arrays.
Array
(
[0] => Array
(
[fromWho] => [email protected]
)
[1] => Array
(
[tid] => 2013-05-05 23:35
)
[2] => Array
(
[answer] => Company
)
[3] => Array
(
[name] => message
)
[4] => Array
(
[label] => Message
)
[5] => Array
(
[fromWho] => [email protected]
)
[6] => Array
(
[tid] => 2013-05-05 23:35
)
[7] => Array
(
[answer] => Star Company
)
[8] => Array
(
[name] => name
)
[9] => Array
(
[label] => Name
)
)
I want the array like this array keys order doesn't matter:
Array
(
[0] => Array
(
[label] => Message
[name] => message
[answer] => Company
[tid] => 2013-05-05 23:35
[fromWho] => [email protected]
)
[0] => Array
(
[label] => Name
[name] => name
[answer] => Star Company
[tid] => 2013-05-05 23:35
[fromWho] => [email protected]
)
)
Answer
Solution:
Usearray_chunk()
to group the array into chunks of 5 elements. Then you can convert each chunk into an associative array.
$chunks = array_chunk($data, 5);
$result = array_map(function($chunk) {
$arr = [];
foreach ($chunk as $entry) {
foreach ($entry as $key => $val) {
$arr[$key] = $val;
}
}
return $arr;
}, $chunks);
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: using $this when not in object context laravel
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.