Jump to content

Merge php array elements that have the same name


funstad

Recommended Posts

how could i merge my array element so the print below results in the following output

 

End result should be like this:

[name] weight => heavy, less, diff

[name] height => centimer

 

Instead of:

[name] weight => heavy

[name] weight => less

[name] weight => diff

[name] height => centimer

 

Current output:

Array
(
    [Andere kenmerken] => Array
        (
            [0] => Array
                (
                    [name] => weight
                    [value] => heavy
                )

            [1] => Array
                (
                    [name] => weight
                    [value] => less
                )

            [2] => Array
                (
                    [name] => weight
                    [value] => diff
                )

            [3] => Array
                (
                    [name] => weight
                    [value] => less
                )

            [4] => Array
                (
                    [name] => height
                    [value] => centimer
                )

        )

)
Link to comment
Share on other sites

You need to loop through that array and add each of the items to another array. You need to check to see if each element already exists and create it if it doesn't, or else add the value to another array for each name. So weight and height would both be arrays, with one or more values.

Link to comment
Share on other sites

Thanks for your explanation i am using the code below now and it does the job :Pleased:

        $result = [];
            foreach($not_distributed_feature_n_v as $v) {
                if(!isset($result[$v["name"]])) {
                    $result[$v["name"]]["name"] = $v["name"];
                    $result[$v["name"]]["value"] = $v["value"];
                } else {
                    $result[$v["name"]]["value"] .= ", " . $v["value"];
                }
            }
            $output[$this->l('Other Features')] = array_values($result);
        }
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...