簡體   English   中英

多維數組將相同id(key)的值連接在一起

[英]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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM