Calculate the highest duplicate integers of two associative arrays

后端 未结 4 1736
清歌不尽
清歌不尽 2021-01-25 11:19

Given 2 associative arrays:

$fruits  = array ( \"d\" => \"lemon\", \"a\" => \"orange\", \"b\" => \"banana\", \"c\" => \"apple\" );
$fruits2 = array          


        
相关标签:
4条回答
  • 2021-01-25 11:54

    You're probably chasing the wrong solution. To find the highest duplicate in an array I'd use this (PHP 5.3+ syntax):

    max(array_keys(array_filter(array_count_values($array), function ($i) { return $i >= 2; })))
    

    Do this for both arrays and compare which result is higher. Trying to compare both against each other at the same time is too convoluted.

    0 讨论(0)
  • 2021-01-25 12:04

    Got it working this way :

    $n = count($fruits);
    for ( $i = 0; $i < $n; $i++)
    {
      $cur_vals_1 = each ($fruits);
      $cur_vals_2 = each ($fruits2);
    
      $sum1 += $cur_vals_1['key'] * $cur_vals_1['value'];
    
      ...
    }
    
    0 讨论(0)
  • 2021-01-25 12:11

    Use array array_values ( array $input ) function and compare them.

     $value1=array_values($fruits);
     $value2=array_values($fruits2);
    
     for ( $i = 0; $i < count($value1); $i++)
     {
       $test[] = $value1[$i] == $value2[$i] ? TRUE : FLASE;
     }
    
    0 讨论(0)
  • 2021-01-25 12:21

    You don't need the ternary operator.
    Also, be careful with count() as it will fail if your array is null.
    They also need to be equal lengths or you'll get an error.

    if( is_array($value1)  && is_array($value2) && count($value1)==count($value2) ) {
        for ( $i = 0; $i < count($value1); $i++)
        {
            $test[] = ($value1[$i] == $value2[$i]);
        }
    }
    
    0 讨论(0)
提交回复
热议问题