Vincent Decaux
Vincent Decaux

Reputation: 10714

PHP Mysql group array response

I have a query using a join on 2 tables which returns something like this :

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'
    )
)

Is there a way to get an Array like this one :

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

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

I want to group some indexes. For now, I use a loop and a if condition. But I want to know if someone use an other way.

Upvotes: 3

Views: 137

Answers (2)

Jaimin
Jaimin

Reputation: 872

Try to implement this

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

}

for me its working..

Upvotes: 0

vincenth
vincenth

Reputation: 1792

As far as I know, there is no other way.

You can use Mysql GROUP_CONCAT, which will help you get this array :

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

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

You might be able to split the image string using array_map :

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

    return $result;
});

(Code might need some tuning to suit your need)

Upvotes: 1

Related Questions