如果id(key)值与其他id(key)值相同,如何连接键值
PHP
$locations = Array(
[0] => Array(
"id" => 1,
"latitude" => "51.541561",
"longitude", => "84.215",
"content", => "The quick brown"
)
[1] => Array(
"id" => 1,
"latitude" => "51.541561",
"longitude", => "84.215",
"content", => "fox jumps over the lazy dog"
)
[2] => Array(
"id" => 3,
"latitude" => "12.541561",
"longitude", => "32.215",
"content", => "Another content"
)
)
我想这样做:
$locations = Array(
[0] => Array(
"id" => 1,
"latitude" => "51.541561",
"longitude", => "84.215",
"content", => "The quick brown fox jumps over the lazy dog"
)
[2] => Array(
"id" => 3,
"latitude" => "12.541561",
"longitude", => "32.215",
"content", => "Another content"
)
)
基本上,如果id(key)与其他id(key)值相同,我想连接内容(key)中的值。
非常感谢任何帮助。
答案 0 :(得分:2)
试试这个 -
$array = array();
foreach ($yourArray as $val) {
if (!array_key_exists($val['id'], $array)) {
$array[$val['id']] = $val;
} else {
$array[$val['id']]['content'] .= ' '.$val['content'];
}
}
答案 1 :(得分:0)
希望这可以帮到你:)
/**
* merge 2 arrays and return a new merged array. if same same key exists it will overwrite , unlike array_merge_recursive
* @param $a
* @param $b
* @return array|mixed
*/
public static function mergeArray($a,$b){
$args=func_get_args();
$res=array_shift($args);
while(!empty($args))
{
$next=array_shift($args);
foreach($next as $k => $v)
{
if(is_integer($k))
isset($res[$k]) ? $res[]=$v : $res[$k]=$v;
elseif(is_array($v) && isset($res[$k]) && is_array($res[$k]))
$res[$k]=self::mergeArray($res[$k],$v);
else
$res[$k]=. $v;
}
}
return $res;
}