【问题标题】:How to compare inner multidimensional array by keys如何按键比较内部多维数组
【发布时间】:2021-12-28 12:59:14
【问题描述】:
$questionsByLanguageIds = [
 2 =>[
  0 => 2439,
  1 => 2435,
  2 => 2450,
 ],
 5 => [
  0 => 2440
  1 => 2435
  2 => 2451,
 ]
]

我有一个数组,其中包含按语言 id 分组的问题 id(本例中为 2,5)。我需要为每种语言的问题找到不同但仅在同一索引内的问题 ID。

例子:

  1. $questionsByLanguageIds[2][0] == $questionsByLanguageIds[5][0]
    2439 与 2440 不同。如果我发现这种差异,我需要从数据库中删除 id 为 2440 的问题。参考问题 id 将是第一语言的 id,在本例中为 2439。

  2. $questionsByLanguageIds[2][1] == $questionsByLanguageIds[5][1] 2435 等于 2435。忽略循环并继续。

我怎样才能在动态上实现这一点?

到目前为止,这是我的代码:

$fieldLanguages = [2,5];
    for($i=0;  $i < count($fieldLanguages); $i++){
        if($i > 0){
            if( !(array_diff($questionsByLanguageIds[$fieldLanguages[$i]], $questionsByLanguageIds[$fieldLanguages[$i-1]])==[] && array_diff($questionsByLanguageIds[$fieldLanguages[$i]],$questionsByLanguageIdse[$fieldLanguages[$i-1]])==[]) ){
                //has difference
            }
        }
    }

【问题讨论】:

    标签: php arrays multidimensional-array


    【解决方案1】:

    您只需对要从中删除值的数组执行类似的操作:

    unset($questionsByLanguageIds[2][0]);
    

    如果元素值不匹配,则使用continue;

    【讨论】:

      【解决方案2】:

      您可以使用array_diff_assoc 来获取与引用数组不同的 ID。

      $questionsByLanguageIds = [
       2 =>[
        0 => 2439,
        1 => 2435,
        2 => 2450,
       ],
       5 => [
        0 => 2440,
        1 => 2435,
        2 => 2451,
       ]
      ];
      
      /* Reversing the array because array_diff_assoc returns values
         from the first array that do not exist in others. */
      $nonMatchingQuestions = array_diff_assoc(...array_reverse($questionsByLanguageIds));
      /*
        in this example this would be the same as
        array_diff_assoc($questionsByLanguageIds[5], questionsByLanguageIds[2])
      */
      /*
      array(2) {
        [0] =>
        int(2440)
        [2] =>
        int(2451)
      }
      */
      

      【讨论】:

        猜你喜欢
        • 2019-08-23
        • 1970-01-01
        • 2020-03-07
        • 1970-01-01
        • 2012-11-24
        • 1970-01-01
        • 1970-01-01
        • 2017-11-29
        相关资源
        最近更新 更多