3

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.

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Nice, it works. I didn't know this way. Can be useful for simple datas. Thanks. I'll wait if someone have other answers.
0

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..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.