0

I have an array of records I want to create a separate array of skills and want to remove duplicate values, unset not providing desired result somehow, I am not able to find out what's wrong. For example I have record (a) in first skills array at index 0 and I have same record in last skills array at index 1 , I just want to remove any duplicate records but unset removing other records also.

$x = 0;
$y = 0;
$z = 0;

$data = array();


$all_data = array ( 0 => array ( "fname" => "Ann",  "skills" => array ( 0 => "a", 1 => "b" )),
1 => array ( "fname" => "Bxx",  "skills" => array ( 0 => "c", 1 => "d" )),
2 => array ( "fname" => "Sdd",  "skills" => array ( 0 => "e", 1 => "a" ))
);


while( $x < count($all_data)){

    while($y < count($all_data[$x]['skills'])){

        $data[$x] = $all_data[$x]['skills'];

        if (in_array($data[$x][$y], $data[$x])){
            unset($data[$x][$y]);
        }

        $y++;
    }

    $y = 0;


    $x++;
}

The result I am getting is this

Array
(
 [0] => Array
    (
        [0] => a
    )

[1] => Array
    (
        [0] => c
    )

[2] => Array
    (
        [0] => e
        [1] => a
    )

)

I am expecting

Array
 (
  [0] => Array
    (
        [0] => a
        [1] => b
    )

[1] => Array
    (
        [0] => c
        [1] => d
    )

[2] => Array
    (
        [0] => e
    )

)

1 Answer 1

1

You could try something like this :

$keys=[];
foreach ($all_data as $index1 => $item) {
    if (!isset($item['skills'])) continue;
    foreach ($item['skills'] as $index2 => $value) {
        if (!in_array($value, $keys)) {
            $data[$index1][] = $value ;
            $keys[] = $value ;
        }
    }
}
unset($keys);

print_r($data);

Outputs :

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
            [1] => d
        )

    [2] => Array
        (
            [0] => e
        )

)
Sign up to request clarification or add additional context in comments.

3 Comments

ok please can you explain this one if (!isset($item['skills'])) continue;
@NickTaylor It is a just a test to avoid warnings about using $item['skills']. But it could not be yours purpose if you always have a skills index.
hmmm ok gr8. Thank you dear.

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.