B
B
Beeshop872021-06-14 21:26:42
PHP
Beeshop87, 2021-06-14 21:26:42

How to compare multiple arrays and return total value in php?

Hello! I can't find a solution at all. Any ideas?
We have this array:

$array {
  [0]=>
  array(1) {
    [0]=>
    string(2) "28"
  }
  [1]=>
  array(2) {
    [0]=>
    string(2) "28"
    [1]=>
    string(2) "29"
  }
}


And an array for comparison:

$filter {
  [0]=>
  string(2) "28"
  [1]=>
  string(2) "29"
}


Tell me how to compare $array with the comparison array to get only 28 ?

this code returns all matches.

foreach ($array as $item) {

  $arResult = array_intersect($filter, $item);

}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
N, 2021-06-14
@Beeshop87

To understand the logic...

<?php

$ar1 = [
        [28],
        [28, 29]
    ];
    
$ar2 = [28, 29];

$arRes = [];
$arResult = [];

foreach($ar1 as $arItems) {
    
    foreach($arItems as $item) {
        
        if(in_array($item, $ar2))
            if(!isset($arRes[$item]))
                    $arRes[$item] = 1;
                else
                    $arRes[$item]++;
        
    }
    
}

$allAr1 = count($ar1);

foreach($arRes as $k => $v)
    if($v >= $allAr1)
        $arResult[] = $k;
        
print_r($arResult);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question