Home > OS >  Compare some keys from 2 multidimensional arrays
Compare some keys from 2 multidimensional arrays

Time:03-26

I need to compare the value of the keys from 2 multidimensional arrays :

array1 [
  0 => [
    "designation" => "multiple"
    "type" => "AAAAA"
    "model" => "B"
    "isSim" => false
    "order" => 5
  ]
etc...
]

array2 [
  0 => [
    "designation" => "single"
    "type" => "AACAA"
    "model" => "B"
  ]
etc...
]

I would like to compare 'designation', 'type', 'model' from array1 to array2 and if the values are the same, I will set the 'isSim' to true.

I know how to set 'isSim' but I've got some difficulties to compare the 2 multidimensional arrays

NOTE => The 2 arrays don't have the same size

CodePudding user response:

Should be something like the following:

$basearray = [["designation" => "multiple", 
    "type" => "AAAAA",
    "model" => "B",
    "isSim" => false,
    "order" => 5 ]];

$compareto = [["designation" => "single"
    "type" => "AACAA"
    "model" => "B"]];

foreach($basearray as $base){
    foreach($compareto as $compare){
        if($compare["designation"] == $base["designation"] && 
           $compare["type"] == $base["type"] &&
           $compare["model"] == $base["model"]){
           
           $base["isSim"] = true;
       }
    }
}

Additionally if you are sure that there can only be one array in $compareto that is the same as an array from $basearray you can put a break; after $base["isSim"] = true;.

  • Related