Home > Mobile >  How to compare inner multidimensional array by keys
How to compare inner multidimensional array by keys

Time:11-18

$questionsByLanguageIds = [
 2 =>[
  0 => 2439,
  1 => 2435,
  2 => 2450,
 ],
 5 => [
  0 => 2440
  1 => 2435
  2 => 2451,
 ]
]

I have an array with questions ids grouped by languages ids (2,5 in this example). I need to find for every language questions ids that are different but only within the same index.

examples:

  1. $questionsByLanguageIds[2][0] == $questionsByLanguageIds[5][0]
    2439 is different from 2440. if I found this difference than I need to delete question with id 2440 from database. The reference question id will be id from first language, in this case 2439.

  2. $questionsByLanguageIds[2][1] == $questionsByLanguageIds[5][1] 2435 is equal with 2435. Ignore the loop and continue.

How can I achieve this dinamically?

So far this is my code:

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

CodePudding user response:

You'd simply do something like this for the array you want the value removed from:

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

And use continue; if the element values do not match.

CodePudding user response:

You could use array_diff_assoc to get the ID's that are different from the reference array.

$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)
}
*/
  • Related