0

I want to concat values of array with same key Example:

[0] => Array
        (
            [0] => A
            [1] => XYZ
        )

[1] => Array
    (
        [0] => B
        [1] => ABC
    )

[2] => Array
    (
        [0] => A
        [1] => LMN
    )

[3] => Array
    (
        [0] => B
        [1] => PQR
    )
)

Expected output:

[0] => Array
        (
            [0] => A
            [1] => XYZ,LMN
        )

[1] => Array
    (
        [0] => B
        [1] => ABC,PQR
    )
)
1
  • 1
    Have you tried something? Commented Jan 4, 2016 at 21:17

4 Answers 4

1

A simple solution uses the PHP function array_reduce():

// The input array you posted in the question
$input = array(
    array('A', 'XYZ'),
    array('B', 'ABC'),
    array('A', 'LMN'),
    array('B', 'PQR'),
);

// Reduce the array to a new array that contains the data aggregated as you need
$output = array_reduce(
    // Process each $item from $input using a callback function
    $input,
    // The callback function processes $item; the partial result is $carry
    function (array $carry, array $item) {
        // Extract the key into a variable
        $key = $item[0];
        // If the key was encountered before
        // then a partial entry already exists in $carry
        if (isset($carry[$key])) {
            // Append the desired value to the existing entry
            $carry[$key][1] .= ','.$item[1];
        } else {
            // Create a new entry in $carry (copy $item to key $key for quick retrieval)
            $carry[$key] = $item;
        }
        // Return the updated $carry
        return $carry;
    },
    // Start with an empty array (it is known as $carry in the callback function)
    array()
);

// $output contains the array you need
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

$final = array();

foreach ($array_items as $item)
{
    $key = $item[0];
    $found_index = -1;

    for ($i=0; $i<count($final); $i++)
    {
        if ($key == $final[$i][0])
        {
            $found_index = $i;
            break;
        }
    }

    if ($found_index == -1)
    {
        $final_item = array();
        $final_item[0] = $key;
        $final_item[1] = $item[1];
        $final[] = $final_item;
    }
    else
    {
        $final[$found_index][1] .= ",".$item[1];
    }
}

We create a new array $final, and loop through your old array $array_items. For each item, we see if there is already an item in $final that has the same [0] index. If it doesn't exist, we create it and add the initial string to the [1] index. If it does exist, we just have to add the string onto the end of the [1] index.

Try it, substituting $array_items for whatever your array is called, let me know if it works.

Comments

0

Check my solution. It should work fine. I hope it will help you much.

$result = $passed_keys = $extended_arr = [];
foreach ($arr as $k => $value) {
    for($i = $k + 1; $i < count($arr); $i++){
        if ( $value[0] == $arr[$i][0] ){    // compare each array with rest subsequent arrays
            $key_name = $value[0];
            if (!array_key_exists($key_name, $result)){
                $result[$key_name] = $value[1] .",". $arr[$i][1];
            } else {
                if (!in_array($i, $passed_keys[$key_name])) {
                    $result[$key_name] .= ",". $arr[$i][1];

                }
            }
            $passed_keys[$key_name][] = $i; // memorizing keys that were passed
        }
    }
}
array_walk($result, function($v, $k) use(&$extended_arr){
    $extended_arr[] = [$k, $v];
});

The result is in $extended_arr

Comments

0

My solution, creates a custom key which makes identifying the letter much easier. This removes the need to continuously iterate through each array, which can become a major resources hog.

<?php
$inital_array = array(
    array('A','XYZ'),
    array('B','ABC'),
    array('A','LMN'),
    array('B','PQR')
);

$concat_array = array();

foreach($inital_array as $a){
    $key = $a[0];

    if( !isset($concat_array[$key]) ){
        $concat_array[$key] = array($key,'');
    }

    $concat_array[$key][1] .= (empty($concat_array[$key][1]) ? '' : ',').$a[1];
}

$concat_array = array_values($concat_array);

echo '<pre>',print_r($concat_array),'</pre>';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.