2016-08-05 52 views
3

我必须使用2台联接返回像这样的查询:PHP的MySQL组阵列响应

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条件。但我想知道是否有人使用其他方式。

回答

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; 
}); 

(代码可能需要一些调整,以适合你的需求)

+0

不错,它的工作原理。我不知道这种方式。对简单数据可能有用。谢谢。如果有人有其他答案,我会等待。 –

0

试着实现这个

$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; 
    } 

} 

对我来说它的工作..