多维数组连接相同 id(键) 的值


Multidimensional array concatenate values of the same id(key)

如果 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) 值相同,我想连接 content(key) 中的值。

任何帮助将不胜感激。

试试这个 -

$array = array();
foreach ($yourArray as $val) {
    if (!array_key_exists($val['id'], $array)) {
        $array[$val['id']] = $val;
    } else {
        $array[$val['id']]['content'] .= ' '.$val['content'];
    }
}

希望这对你:)

/**
 * 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;
}