在关联数组中比较两个不同的值PHP [duplicate]

hmmo2u0o  于 2023-06-04  发布在  PHP
关注(0)|答案(1)|浏览(200)

此问题已在此处有答案

Remove duplicate sets of values in 2d array (regardless of the order or keys in each row)(3个答案)
7天前关闭
通过值prep_first和prep_second比较数组中的所有元素,当prep_first和prep_second等于其他prep_second和prep_first时,删除该键。示例$array=

Array
    (
        [0] => Array
            (
                [description] => ...
                [prof] => ...
                [risk] => high
                [prep_first] => potassium
                [prep_second] => oxygen
            )
        [1] => Array
            (
                [description] => ...
                [prof] => ...
                [risk] => high
                [prep_first] => ethanol
                [prep_second] => sodium
            )
        [2] => Array
            (
                [description] => ...
                [prof] => ...
                [risk] => high
                [prep_first] => oxygen
                [prep_second] => potassium
            )
    
    )

需要

Array
(
    [0] => Array
        (
            [description] => ...
            [prof] => ...
            [risk] => high
            [prep_first] => potassium
            [prep_second] => oxygen
        )
    [1] => Array
        (
            [description] => ...
            [prof] => ...
            [risk] => high
            [prep_first] => ethanol
            [prep_second] => sodium
        )
)

我尝试了两个循环foreach,但无法过滤示例

$res = [];
foreach ($array as $value) {
      $first = $value['prep_first'];
      $second = $value['prep_second'];
      foreach ($array as $value1) {
        $first1 = $value1['prep_first'];
        $second1 = $value1['prep_second'];
            if ($first !== $second1 && $second !== $first1) {
                  $res[] = $val;
            }

      }
}

谢谢你

dfty9e19

dfty9e191#

  • 迭代这些值,将每个组合保存在$combinations
  • sort()组合,因此顺序无关紧要
  • 仅将以前未保存的组合添加到$res
$res = [];
$combinations = [];

foreach ($array as $value) {
    $combination = [$value['prep_first'], $value['prep_second']];
    sort($combination);

    if (!in_array($combination, $combinations)) {
        $combinations[] = $combination;
        $res[] = $value;
    }
}

相关问题