2015-10-25 73 views
0

傍晚!堆疊數組元素

我真的對此毫無頭緒,想到自己我會訴諸你們一些指導。我有一個數組,從一個MySQL表直接進賬,看起來是這樣的:

array(106) { 
    [...] 
    [32]=> 
    array(4) { 
    ["x"]=> 
    int(3) 
    ["y"]=> 
    int(5) 
    ["z"]=> 
    int(7) 
    ["image"]=> 
    string(14) "ground/grass/1" 
    } 
    [33]=> 
    array(4) { 
    ["x"]=> 
    int(3) 
    ["y"]=> 
    int(5) 
    ["z"]=> 
    int(8) 
    ["image"]=> 
    string(16) "objects/nature/1" 
    } 
    [34]=> 
    array(4) { 
    ["x"]=> 
    int(4) 
    ["y"]=> 
    int(5) 
    ["z"]=> 
    int(7) 
    ["image"]=> 
    string(14) "ground/grass/1" 
    } 
    [...] 
} 

我想要做的是合併在xy密鑰是相同的元素的圖像,創建一個新的數組,其中z值成爲鍵。可以有兩個以上的元素具有相同的xy值,但z這些元素的值從未相同。有點難以解釋,但所需的輸出看起來是這樣的:

array(106) { 
    [...] 
    [32]=> 
    array(4) { 
    ["x"]=> 
    int(3) 
    ["y"]=> 
    int(5) 
    ["z"]=> 
    int(7) 
    ["image"]=> 
     array(2) { 
     [7]=> 
     string(14) "ground/grass/1" 
     [8]=> 
     string(16) "objects/nature/1" 
     } 
    } 
    [34]=> 
    array(4) { 
    ["x"]=> 
    int(4) 
    ["y"]=> 
    int(5) 
    ["z"]=> 
    int(7) 
    ["image"]=> 
    string(14) "ground/grass/1" 
    } 
    [...] 
} 

我很樂意爲您提供我的進步,到目前爲止,但事實是,我在這一個毫無頭緒。 MySQL表看起來像這樣:

| id | x | y | z |    image | 
+----+----+----+----+--------------------+ 
| 1 | 3 | 5 | 7 | 'ground/grass/1' | 
| 2 | 3 | 5 | 8 | 'objects/nature/1' | 

對不起,長期的問題。提前致謝!

回答

1

你有沒有想過在你的SQL查詢中使用GROUP_CONCAT?類似於

SELECT x, y, GROUP_CONCAT(CONCAT(z,':',image)) as image 
FROM your_table 
GROUP BY x, y 

函數的文檔here

+0

是啊,我一直在尋找它,但問題是,我失去了z'的'值一/一些在做這件事的時候。我會多玩一點,看看我能做些什麼。 –

+1

伊斯蘭會議組織 - 你可以通過在其中嵌套一個CONCAT(見上面的編輯)。 – wogsland

1

這裏就是我所做的,以達到預期的效果:

我使用的查詢從wogsland’s答案:

SELECT x, y, GROUP_CONCAT(CONCAT(z,':',image)) as image 
FROM your_table 
GROUP BY x, y 

然後,我通過查詢(其中$map包含的結果)的結果循環:

foreach ($map as $i => $tile) { 
    $map[$i]['image'] = explode(',', $tile['image']); 
    $images = $map[$i]['image']; 
    $map[$i]['image'] = []; 
    foreach ($images as $image) { 
     $image = explode(':', $image); 
     $map[$i]['image'][$image[0]] = $image[1]; 
    } 
} 
0

這是一種醜陋的做法,幾乎你想在PHP中做什麼。該陣列是$ ARR開頭和$出新的數組:

$res = array(); 
$out = array(); 
foreach($arr as $item) { 
    $res[$item['x']][$item['y']][$item['z']] = $item['image']; 
} 

foreach($res as $k => $v) { 
    foreach($v as $n => $m) { 
     $out[] = array('x' => $k, 'y' => $n, 'image' => $m); 
    } 
} 

輸出將是:

array(106) { 
    [...] 
    [32]=> 
    array(4) { 
    ["x"]=> 
    int(3) 
    ["y"]=> 
    int(5) 
    ["image"]=> 
     array(2) { 
     [7]=> 
     string(14) "ground/grass/1" 
     [8]=> 
     string(16) "objects/nature/1" 
     } 
    } 
    [34]=> 
    array(4) { 
    ["x"]=> 
    int(4) 
    ["y"]=> 
    int(5) 
    ["image"]=> 
     array(1) { 
     [7]=> 
     string(14) "ground/grass/1" 
     } 
    } 
    [...] 
} 

的「Z」值被刪除,因爲它沒有真正目的'image'始終是一個以'z'值爲關鍵字的數組!

我會用三維陣列$res['x']['y']['z']並跳過最後一步......