Jump to content
funstad

Merge php array elements that have the same name

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
                )

        )

)

Share this post


Link to post
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.

Share this post


Link to post
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);
        }

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...