首頁 >後端開發 >php教程 >PHP 数组中如果有一个元素相同,如何拼接其他元素

PHP 数组中如果有一个元素相同,如何拼接其他元素

WBOY
WBOY原創
2016-06-23 13:34:45793瀏覽

比如原数组是这样的
array(3) {
[0] => array(6) {
["pla_id"] => string(3) "298"
["user_id"] => string(1) "1"
["due_in"] => string(15) "8.33"
}
[1] => array(6) {
["pla_id"] => string(3) "976"
["user_id"] => string(1) "1"
["due_in"] => string(15) "338.90"
}
[2] => array(6) {
["pla_id"] => string(3) "56"
["user_id"] => string(1) "2"
["due_in"] => string(15) "25.6"
}}
因为数组中的user_id=1 是一样的
要得到最后这样数组,要怎么写(就是把user_id相同的其他元素拼接在一起)?
array(3) {
[0] => array(6) {
["pla_id"] => string(3) "298,976"
["user_id"] => string(1) "1"
["due_in"] => string(15) "8.33,338.90"
}
[1] => array(6) {
["pla_id"] => string(3) "56"
["user_id"] => string(1) "2"
["due_in"] => string(15) "25.6"
}}


回复讨论(解决方案)

$a = array(  array(    "pla_id" => "298",    "user_id" => "1",    "due_in" => "8.33",  ),  array(    "pla_id" => "976",    "user_id" => "1",    "due_in" => "338.90",  ),  array(    "pla_id" => "56",    "user_id" => "2",    "due_in" => "25.6",  ));$b = array();foreach($a as $v) {  if(! isset($b[$v['user_id']])) $b[$v['user_id']] = $v;  else $b[$v['user_id']]["due_in"] .= ',' . $v["due_in"];}var_dump(array_values($b));
array(2) {  [0]=>  array(3) {    ["pla_id"]=>    string(3) "298"    ["user_id"]=>    string(1) "1"    ["due_in"]=>    string(11) "8.33,338.90"  }  [1]=>  array(3) {    ["pla_id"]=>    string(2) "56"    ["user_id"]=>    string(1) "2"    ["due_in"]=>    string(4) "25.6"  }}

$a = array(  array(    "pla_id" => "298",    "user_id" => "1",    "due_in" => "8.33",  ),  array(    "pla_id" => "976",    "user_id" => "1",    "due_in" => "338.90",  ),  array(    "pla_id" => "56",    "user_id" => "2",    "due_in" => "25.6",  ));$b = array();foreach($a as $v) {  if(! isset($b[$v['user_id']])) $b[$v['user_id']] = $v;  else $b[$v['user_id']]["due_in"] .= ',' . $v["due_in"];}var_dump(array_values($b));
array(2) {  [0]=>  array(3) {    ["pla_id"]=>    string(3) "298"    ["user_id"]=>    string(1) "1"    ["due_in"]=>    string(11) "8.33,338.90"  }  [1]=>  array(3) {    ["pla_id"]=>    string(2) "56"    ["user_id"]=>    string(1) "2"    ["due_in"]=>    string(4) "25.6"  }}


谢谢啊 太感谢了
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn