php - 堆叠数组元素

标签 php mysql arrays

晚上好!

我对此真的一无所知,我想我会向你们寻求一些指导。我有一个数组,直接从 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 code> 值成为键。可以有两个以上的元素具有相同的 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' |

抱歉问了这么长的问题。提前致谢!

最佳答案

这是我为达到预期结果所做的事情:

我使用了来自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]; 
    }
}

关于php - 堆叠数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33334929/

相关文章:

PHP 内联写入对象

php 到 mysql 更新帖子不起作用

php - 对 MySQL 中的列中的值求和并对它们进行分组

javascript - 在以下情况下,当错误来自PHP作为对Ajax请求的响应时,如何显示警报?

php - 对保持原始时间不变 MySQL 的行进行更新查询

php - Laravel5 Eloquent : How to get a few articles from special condition?

php - 如何将从查询返回的值数组转换为逗号分隔值

arrays - 聊天中 Trolls 消息的 Ruby 过滤器(用重复值填充数组)

php - Wordpress数据库查询多少次才算正常?

数据库中的 PHP 和标签