php - 将数组中的值复制到多维数组

时间:2016-06-05 08:37:37

标签: php arrays multidimensional-array

我有一个包含多个交易的数组,其中多个交易来自同一个电子邮件地址。

其中一些交易在client密钥中有一个值。其他人不会。

我想在所有匹配的数组中使用相同的client密钥复制填充的email_address密钥,以便始终在client密钥中包含数据。

我的阵列示例:

Array
(
    [1] => Array
        (
            [client] => John John
            [email_address] => john@john.com
        )

    [3] => Array
        (
            [client] => Kevin Kevin
            [email_address] => kevin@kevin.com
        )

    [5] => Array
        (
            [client] => 
            [email_address] => john@john.com
        )

)

我想要达到的目的是确保Array [5] client密钥与Array [1]具有相同的值,因为它是同一个客户端(基于{{ 1}}键)。

结果数组的示例:

email_address

如何通过数组确保匹配的数组(基于Array ( [1] => Array ( [client] => John John [email_address] => john@john.com ) [3] => Array ( [client] => Kevin Kevin [email_address] => kevin@kevin.com ) [5] => Array ( [client] => John John [email_address] => john@john.com ) ) 键)始终具有相同的email_address键?

2 个答案:

答案 0 :(得分:1)

使用array_columnarray_uniquearray_fliparray_count_valuesarray_filterarray_intersect_key函数的解决方案(此解决方案也非常适合用于处理多组"客户"条目与#34; email_address"):

// supposing $arr is your initial array

$ties = array_flip(array_unique(array_column($arr, "email_address", "client")));
$counts = array_filter(array_count_values(array_column($arr, "email_address")), function($v){
    return $v > 1;  // getting number of entries with same 'email' attribute
});    
$relations = array_intersect_key($ties, $counts);   // contains pairs of relative email/client entries, like "[john@john.com] => John John"

foreach ($arr as &$client) {
    if (!$client['client'] && key_exists($client['email_address'], $relations)) {
        $client['client'] = $relations[$client['email_address']];
    }
}

print_r($arr);

输出:

Array
(
    [1] => Array
        (
            [client] => John John
            [email_address] => john@john.com
        )

    [3] => Array
        (
            [client] => Kevin Kevin
            [email_address] => kevin@kevin.com
        )

    [5] => Array
        (
            [client] => John John
            [email_address] => john@john.com
        )
)

答案 1 :(得分:0)

您可以创建一个将电子邮件地址与客户端相关联的中间数组。像这样:

['-', '/', '.', '_']

然后填写缺少的客户端单元格:

$intermediateArray = [];

foreach ($inputArray as $row) {
  if (isset($row['client']) {
    $intermediateArray[$row['email_address']] = $row['client']
  }
}

更有效的解决方案是可能的,但这个似乎是最简单的。