【问题标题】:PHP Mysql group array responsePHP Mysql 组数组响应
【发布时间】:2016-08-05 14:11:54
【问题描述】:

我有一个使用 2 个表的连接的查询,它返回如下内容:

Array
(
[0] => Array
    (
        [id] => 1
        [description] => 'Test'
        [image] => '1.jpg'
    )

[1] => Array
    (
        [id] => 1
        [description] => 'Test'
        [image] => '2.jpg'
    )

[2] => Array
    (
        [id] => 2
        [description] => 'Test 2'
        [image] => '11.jpg'
    )
)

有没有办法得到这样的数组:

Array
(
[0] => Array
    (
        [id] => 1
        [description] => 'Test'
        [image] => array('1.jpg', '2.jpg')
    )

[2] => Array
    (
        [id] => 2
        [description] => 'Test 2'
        [image] => '11.jpg'
    )
)

我想对一些索引进行分组。现在,我使用循环和 if 条件。但我想知道是否有人使用其他方式。

【问题讨论】:

    标签: php mysql arrays


    【解决方案1】:

    据我所知,没有其他办法。

    你可以使用Mysql GROUP_CONCAT,它会帮助你得到这个数组:

    Array
    (
    [0] => Array
        (
            [id] => 1
            [description] => 'Test'
            [image] => '1.jpg 2.jpg'
        )
    
    [2] => Array
        (
            [id] => 2
            [description] => 'Test 2'
            [image] => '11.jpg'
        )
    )
    

    您也许可以使用array_map 分割图像字符串:

    $formattedResults = array_map($results, function($result){
        $result['image'] = explode(' ', $result['image']);
    
        return $result;
    });
    

    (代码可能需要一些调整以满足您的需要)

    【讨论】:

    • 很好,它有效。我不知道这种方式。可用于简单数据。谢谢。如果有人有其他答案,我会等待。
    【解决方案2】:

    尝试实现这个

    $result = [];
    
    foreach ($array as $key => $value) {
        $hash = $value['id'];
        if(isset($result[$hash])){
            $temp[] = "{$value['image']}";
            $result[$hash]['image'] = $temp;
        }else{
            $temp   = array();
            $temp[] = $value['image'];
            $result[$hash] = $value;
        }
    
    }
    

    对我来说它的工作..

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-27
      • 2014-07-24
      • 1970-01-01
      • 2012-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多