php数组未设置按预期工作

时间:2018-02-06 07:38:59

标签: php arrays

我有一系列记录,我想创建一个单独的技能数组,并希望删除重复的值,未设置不能以某种方式提供所需的结果,我无法找出错误。例如,我在索引0的第一个技能数组中有记录(a),并且我在索引1的最后一个技能数组中有相同的记录,我只想删除任何重复记录,但也取消设置删除其他记录。

$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++;
}

我得到的结果就是这个

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

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

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

我期待

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

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

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

1 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情:

$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);

输出:

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

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

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

)