sfy
sfy

Reputation: 3238

how to simplify this multi-dimensions associative array?

$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.

Upvotes: 1

Views: 156

Answers (2)

mkasberg
mkasberg

Reputation: 17302

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);

Upvotes: 1

Jonathan
Jonathan

Reputation: 2877

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"
    }
  }
}

Upvotes: 6

Related Questions