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

2 comments:

  1. This is an amazing blog,it gives very helpful messages to us.Besides that Wisen has established as Best Javascript Training in Chennai . or learn thru JavaScript Online Training India. Nowadays JavaScript has tons of job opportunities on various vertical industry

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