string(3) "298"["user_id"] => string(1) "1"["/>  string(3) "298"["user_id"] => string(1) "1"[">

Home >Backend Development >PHP Tutorial >PHP 数组中如果有一个元素相同,怎么拼接其他元素

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

WBOY
WBOYOriginal
2016-06-13 12:19:39912browse

PHP 数组中如果有一个元素相同,如何拼接其他元素
比如原数组是这样的
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(<br />  array(<br />    "pla_id" => "298",<br />    "user_id" => "1",<br />    "due_in" => "8.33",<br />  ),<br />  array(<br />    "pla_id" => "976",<br />    "user_id" => "1",<br />    "due_in" => "338.90",<br />  ),<br />  array(<br />    "pla_id" => "56",<br />    "user_id" => "2",<br />    "due_in" => "25.6",<br />  )<br />);<br />$b = array();<br />foreach($a as $v) {<br />  if(! isset($b[$v['user_id']])) $b[$v['user_id']] = $v;<br />  else $b[$v['user_id']]["due_in"] .= ',' . $v["due_in"];<br />}<br />var_dump(array_values($b));
array(2) {<br />  [0]=>  array(3) {<br />    ["pla_id"]=>    string(3) "298"<br />    ["user_id"]=>    string(1) "1"<br />    ["due_in"]=>    string(11) "8.33,338.90"<br />  }<br />  [1]=>  array(3) {<br />    ["pla_id"]=>    string(2) "56"<br />    ["user_id"]=>    string(1) "2"<br />    ["due_in"]=>    string(4) "25.6"<br />  }<br />}<br /><br />

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn