Tuesday, May 19, 2015

PHP: Group array to unique value

Existing array:
Array
(
    [0] => Array
        (
            [id] => 12
            [name] => John
            [description] => this is a description.
        )

    [1] => Array
        (
            [id] => 57
            [name] => John
            [description] => test description.
        )

    [2] => Array
        (
            [id] => 85
            [name] => Amy
            [description] => testing 123.
        )

)
Apply this:
$result = array();

foreach ($arr as $data) {

        $name = $data['name'];
        if (isset($result[$name])) {
                $result[$name][] = $data;
        } else {
                $result[$name] = array($data);
        }

}
Output:
Array
(
        [John] => Array
        (
                [0] => Array
                (
                        [id] => 12
                        [name] => John
                        [description] => this is a description.
                )

                [1] => Array
                (
                        [id] => 57
                        [name] => John
                        [description] => test description.
                )
        )
        [Amy] => Array
        (
                [0] => Array
                (
                        [id] => 85
                        [name] => Amy
                        [description] => testing 123.
                )
        )
)

Refer: http://stackoverflow.com/questions/12706359/php-array-group

1 comment:

  1. Good one.I appreciate you for sharing this knowledge.Keep writing blog posts.Have a look on custom software development company.please try what custom software service suggested.

    ReplyDelete