$arr1 = array(
1=>array(
'name' => 'a',
'phone'=> '110',
),
2=>array(
'name' => 'b',
'phone'=> '119',
),
3=>array(
'name' => 'a',
'phone'=> '119',
),
4=>array(
'name' => 'b',
'phone'=> '110',
),
);
I spent 3 hours to figure it out,and fails。I wanna merge the phone values to new arrays based on the name key values。 The result like this
$arr2 = array(
1=>array(
'name' => 'a',
'phone'=> array(
1=>'110',
2=>'119',
),
),
2=>array(
'name' => 'b',
'phone'=> array(
1=>'110',
2=>'119',
),
)
);
It's not as easy as it looks.
-
1Here's an answer that shows how to do it in Javascript: stackoverflow.com/questions/24302630/… The logic is the same in PHP, just minor syntax differences.Barmar– Barmar2015年05月06日 16:56:44 +00:00Commented May 6, 2015 at 16:56
2 Answers 2
You need to loop through the array and make a new one.
code
<?php
/** store the results in here **/
$targetArray = [];
/** the data source **/
$sourceArray = [
1 => [
'name' => 'a',
'phone'=> '110',
],
2 => [
'name' => 'b',
'phone'=> '119',
],
3 => [
'name' => 'a',
'phone'=> '119',
],
4 => [
'name' => 'b',
'phone'=> '110',
]
];
foreach($sourceArray as $arr) {
/** create key based off name **/
$targetArray[$arr['name']]['name'] = $arr['name'];
/** add phone numbers as they are found **/
$targetArray[$arr['name']]['phone'][] = $arr['phone'];
}
/** reindex the array **/
$targetArray = array_values($targetArray);
/** see the result **/
var_dump($targetArray);
output
array(2) {
[0]=>
array(2) {
["name"]=>
string(1) "a"
["phone"]=>
array(2) {
[0]=>
string(3) "110"
[1]=>
string(3) "119"
}
}
[1]=>
array(2) {
["name"]=>
string(1) "b"
["phone"]=>
array(2) {
[0]=>
string(3) "119"
[1]=>
string(3) "110"
}
}
}
Sign up to request clarification or add additional context in comments.
4 Comments
Alfwed
if you replace
sort by array_values i'll upvote youJonathan
wrote it quickly without thinking, but yes that is definitely the better way.
sfy
very illuminating and insightful, beautiful codes, thanks a lot. can't believe it can be done in such way.
Jonathan
@Jacob glad I was able to help, don't forget to accept this answer if it's your chosen one :) thx.
Here is one solution:
// Use name as key to merge contact info.
foreach($arr1 as $contactInfo)
{
$arr2[$contactInfo['name']]['name'] = $contactInfo['name'];
$arr2[$contactInfo['name']]['phone'][] = $contactInfo['phone'];
}
// Go back to numeric indexes.
$arr2 = array_values($arr2);
answered May 6, 2015 at 17:04
mkasberg
17.7k3 gold badges46 silver badges48 bronze badges
Comments
lang-php