具有多个值的数组中的PHP组键

时间:2017-05-13 04:41:12

标签: php arrays multidimensional-array associative-array

我有一个这样的数组:

$sendemail= array(
  'apple@yahoo.com' => '123456781234567',
  'apple@yahoo.com' => '013881002296968',
  'cherry@yahoo.com' => '3553220865206561',
  'orange@yahoo.com' => '358805051217453',
  'apple@yahoo.com' => '357998054217777',
  'cherry@yahoo.com' => '013881002296968',
);

我想有这样的输出:

'apple@yahoo.com' => 123456781234567, 013881002296968, 357998054217777
'cherry@yahoo.com' => 3553220865206561, 013881002296968
'orange@yahoo.com' => 358805051217453

能够将密钥用作电子邮件地址,将值用作我的电子邮件伙伴

$email= 'apple@yahoo.com';
$body= '123456781234567, 013881002296968, 357998054217777';
mail($email, 'Your codes', $body);

其他电子邮件地址也一样。

请注意,2个密钥可能具有相同的值(例如apple@yahoo.com和cherry@yahoo.com具有相同的值;该值将发送给它们)

我用'for loop'但没有用。首先,我不能根据电子邮件地址对它们进行分组,其中第二个相同的值不会分配给其他电子邮件地址;比如'013881002296968'应该与apple@yahoo.com和cherry@yahoo.com共享

$sendmail= array(
  '123456781234567' => 'apple@yahoo.com',
  '013881002296968' => 'apple@yahoo.com',
  '3553220865206561' => 'cherry@yahoo.com',
  '358805051217453' => 'orange@yahoo.com',
  '357998054217777' => 'apple@yahoo.com',
  '013881002296968' => 'cherry@yahoo.com',
);
$out = array();
foreach($sendmail as $key=>$value)
    if(array_key_exists($value, $out)) {
         $out[$value][] = $key;
    }
    else {
         $out[$value] = array($key);
    }

输出

array (
  'apple@yahoo.com' => 
  array (
    0 => 123456781234567,
    1 => 013881002296968,
    2 => 357998054217777,
  ),
  'cherry@yahoo.com' => 
  array (
    0 => 3553220865206561,
  ),
  'orange@yahoo.com' => 
  array (
    0 => 358805051217453,
  ),
)

2 个答案:

答案 0 :(得分:1)

这是Kris'的另一种选择。迭代次数少但条件更多的方法:

输入:

$sendmail= array(
  '123456781234567' => 'apple@yahoo.com',
  '013881002296968' => 'apple@yahoo.com',
  '3553220865206561' => 'cherry@yahoo.com',
  '358805051217453' => 'orange@yahoo.com',
  '357998054217777' => 'apple@yahoo.com',
  '013881002296968' => 'cherry@yahoo.com',
);

方法:

foreach($sendmail as $k=>$v){
    if(!isset($out[$v])){$out[$v]='';}  // initialize new element with empty string
    $out[$v].=($out[$v]?',':'').$k;     // concat the values with conditional comma
}
var_export($out);

输出:

array (
  'apple@yahoo.com' => '123456781234567,357998054217777',
  'cherry@yahoo.com' => '013881002296968,3553220865206561',
  'orange@yahoo.com' => '358805051217453',
)

答案 1 :(得分:0)

对结果数组的元素使用implode。 live demo

foreach($sendmail as $key=>$value) {
    $out[$value][] = $key;
}
$out = array_map(function($v){return implode(',', $v);}, $out);