phparray-mergearray-combine

How to combine multiple arrays of duplicate first element (Combine only second element) in PHP?


I've an array of arrays in which I've 2 values in each array first one is personID and second one is Skill, there are multiple skills of same persons I need all same skills to add in an array with single person id. I can't figure how to do it.

Raw Data With Duplicate IDs

$data = array(
    array(1, "Writing"),
    array(3, "Designing"),
    array(1, "Problem Solving"),
    array(3, "Communication"),
    array(5, "Writing"),
    array(5, "Planning and organising"),
    array(5, "Communication"),
    array(1, "Designing"),
    array(2, "Leadership"),
    array(2, "Communication"),
    array(2, "Designing")
);

Need Data Format With Unique Person IDs

$data = array(
    array(1, "Writing", "Problem Solving", "Designing"),
    array(3, "Designing", "Communication"),
    array(5, "Writing", "Planning and organising", "Communication"),
    array(2, "Leadership", "Communication", "Designing")
)

Solution

  • You can loop through the input array $data and build a new array - in this case $dataCombined - with the combined second values:

    <?php
    $firstValues = array();  // array of first values
    $dataCombined = array();   // new array with the combined data
    
    // loop through array $data
    for($i=0;$i<count($data);$i++)
    {
    // first value
    $firstValue = array_values($data[$i])[0];
    // second value
    $secondValue = array_values($data[$i])[1];
    
      // write first values in array $firstValues if missing and fill new array $dataCombined
      if(!in_array($firstValue,$firstValues))
      {
      $firstValues[] = $firstValue ;
      $dataCombined[] = array($firstValue, $secondValue);
      }
      else
      {
        // if first values match combine second values in a new loop
        for($j=0;$j<count($dataCombined);$j++)
        {
        $duplicateFirstValue = array_values($dataCombined[$j])[0];
        $otherSecondValue = array_values($dataCombined[$j])[1]; 
        // case first values match
        if($firstValue === $duplicateFirstValue)
        {
        // fill new array with combined second data
        $dataCombined[$j][1] = $otherSecondValue.",".$secondValue;
        }
        }
      }
    }
    print_r($dataCombined);
    ?>