开发者

PHP Adding multiple associative arrays to new array based on key

I have a few associative arrays that I need to merge together based on there key. so:

array1:
 [person1] => tony 
 [person2] => sandra 

array2:
 [person1] => london
 [person2] => paris        

needs to be :

 array 3
  [person1] => tony , london
  [person2] => sandra , paris

The issue I'm having though is 开发者_运维问答that the key could be any value , so it could be 'person1' or it could be 'hairyOtter' and the array is of varaible size.


Assuming, that every is not multi-dimensional

$merged = array_merge_recursive($array1, $array2);
foreach ($merged as &$entry) {
  if (is_array($entry)) {
    $entry = implode(', ', $entry);
  }
}

The idea is, that array_merge_recursive() creates a new array, if it find two values with the same key. Everything else stays untouched.


I'm sure there are more efficient ways to accomplish this, but for now, this works:

<?php
function combine( $keys, $first, $second ) {
    $args = func_get_args( );
    $keys = array_shift( $args );
    $arrays = $args;
    $result = array( );

    foreach( $keys as $key ) {
        foreach( $arrays as $array ) {
            if( isset( $array[$key] ) ) {
                $result[$key][] = $array[$key];
            }
        }
    }
    return $result;
}

$first = array(
    'person1' => 'tony',
    'person2' => 'sandra'
);

$second = array(
    'person1' => 'london',
    'person2' => 'paris'
);


/**
 * To make sure you get *every* key out of both arrays.
 */
$keys = array_unique( array_merge( array_keys( $first ), array_keys( $second ) ) );

$combined = combine( $keys, $first, $second );
var_dump( $combined );


Two loops should do it. Iterate over each of array1 and array2, initialising array3's keys as you go to an array, and pushing into that array. Here's the first loop

$array3 = array();
foreach (array_keys($array1) as $key) {
    if(!array_key_exists($key, $array3)) {
        $array3[$key] = array();
    }
    array_push($array3[$key], $array1[$key]);
}


$array1 = array('a' => 1, 'b' => 2);
$array2 = array('a' => 3, 'b' => 4, 'c' => 5);

foreach ($array1 as $k => $v) {
  $tArray[$k][] = $v;
}
foreach ($array2 as $k => $v) {
  $tArray[$k][] = $v;
}

foreach ($tArray as $k => $v) {
  $tArray[$k] = implode(',',$tArray[$k]);
}


I would create a multi-dimensional array instead, unless there is a specific reason you can't use one. This way, you would have an array that looks like:

Array
(
[Person1] => Array
  (
  [Name] => Tony
  [City] => London
  )
[Person2] => Array
  (
  [Name] => Sandra
  [City] => Paris
  )
)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜