Konstantinos Natsios
Konstantinos Natsios

Reputation: 2924

PHP Merge object array items

I'm trying to convert this array of objects

Array
(
    [0] => stdClass Object
    (
        [group_name] => 1
        [filter_names] => Array
            (
                [0] => a
            )
    )

    [1] => stdClass Object
    (
        [group_name] => 1
        [filter_names] => Array
            (
                [0] => b
            )
    )
)

to make the objects above merged as one object depending on group_name

and the filter_names to be one array. Ex.

Array
(
    [0] => stdClass Object
    (
        [group_name] => 1
        [filter_names] => Array
            (
                [0] => a,
                [1] = >b
            )
    )
)

Is there any efficient way that we can achieve the above?

A proposed solution from @Djave

        $filter_results = [];
        foreach ($filter_array as $element) {

            // If there is already a group with the same name,
            // just add the element's filter name

            if( array_key_exists($element->group_name, $filter_results)){
                $result[$element->group_name]["filter_names"][] = $element->filter_names;
            }else{

            // Otherwise, create a new record in the result array,
            // with an array wrapping the single filter_name

                $filter_results[] = [
                  "group_name" => $element->group_name,
                  "filter_names" => [ $element->filter_names ]
                ];
            }
        }

Is giving me the following result

Array
(
    [0] => Array
    (
        [group_name] => 1
        [filter_names] => Array
            (
                [0] => Array
                    (
                        [0] => a
                    )

            )

    )

    [1] => Array
    (
        [group_name] => 1
        [filter_names] => Array
            (
                [0] => Array
                    (
                        [0] => b
                    )

            )

    )
)

Upvotes: 0

Views: 75

Answers (1)

Djave
Djave

Reputation: 9329

You could do something like this:

$result = [];
foreach ($data as $element) {

    // If there is already a group with the same name,
    // just add the element's filter name

    if( array_key_exists($element['group_name'], $result)){
        $result[$element['group_name']]["filter_names"][] = $element["filter_names"];
    }else{

    // Otherwise, create a new record in the result array,
    // with an array wrapping the single filter_name

        $result[] = [
          "group_name" => $element['group_name'],
          "filter_names" => [ $element["filter_names"] ]
        ];
    }
}

Upvotes: 1

Related Questions