-1

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")
)
1
  • Welcome to Stack Overflow. Please take the tour to learn how Stack Overflow works and read How to Ask on how to improve the quality of your question. Please show your attempts you have tried and the problems/error messages you get from your attempts. Commented Nov 27, 2022 at 12:47

1 Answer 1

1

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);
?>
Sign up to request clarification or add additional context in comments.

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.