简体   繁体   English

Php Laravel比较2个数组值

[英]Php Laravel Comparing 2 Array Values

Is it possible to compare two Array values ? 是否可以比较两个Array值?

Say: 说:

Array 1>         Array 2>
Values:          Values:
2                 11
36                13
65                11
78                1

Code sample: 代码示例:

If (Array1 >= Array2){

    echo"Not Available";
    }
    else
    {
    echo"Available";
    }

Expected Result: 预期结果:

Array ("Not Available",
       "Available",
       "Available",
       "Available")

You can just do something simple like this: 你可以做这样简单的事情:

function compareArrays(array $array1, array $array2): array
    {
        $itemCount = (count($array1) > count($array2)) ? $array1 : $array2;
        $returnArray = [];
        for($i = 0; $i < count($itemCount); $i++) {
            $returnArray[] = ($array1 >= $array2) ? 'Avalible' : 'Not Avalible';
        }
        return $returnArray;
    }

Main reason being is we don't know from your post if the arrays will always be the same size so you have to compare them to get the larger of the two then use that for the loop. 主要原因是我们从您的帖子中不知道数组是否总是相同的大小,因此您必须比较它们以获得两者中较大的一个然后将其用于循环。 After that it's just simple comparisons. 之后,这只是简单的比较。

You can use a callback function along with array_map function like this. 您可以像这样使用回调函数和array_map函数。

<?php 

function getResult($first, $second)
{
    return $first > $second ? 'Available' : 'Not Available';
}

$firstArray = [1,4,5,6];
$secondArray = [2,3,1,9];

$data = array_map('getResult', $firstArray, $secondArray);

echo '<pre>',print_r($data),'<pre>';

?>

You can customize the logic inside the function for more complex logic as well. 您可以自定义函数内部的逻辑,以获得更复杂的逻辑。 You can add any number of arrays as per your requirement. 您可以根据需要添加任意数量的阵列。 I hope you understand. 我希望你明白。

If both the arrays has same length, you can use for loop as below, 如果两个数组的长度相同,则可以使用for循环,如下所示,

$temp = [];
for($i = 0; $i < count($array1);$i++){
    $temp[] = (($array1[$i] >= $array2[$i]) ? 'Not Available': 'Available');
}
print_r($temp);

Yes it is possible using a simple for loop as bellow: 是的,可以使用简单的for循环:

for($i = 0; $i < count($array1); $i++){
  if($array1[$i] >= $array2[$i]){
    echo "Available"
  }else{
    echo "Not available";
  }
}

Note Here the two array must be of same size. 注意这里两个数组必须大小相同。

If array1 and array2 is always same size, then easy solution 如果array1和array2总是相同的大小,那么很容易解决

$data = [];
foreach($array1 as $key => $value) {
    if (!isset($array2[$key])) { // for safety check for second array index bound
        break;
    }

    $data[] = $value >= $array2[$key] ? 'Not Available' : 'Available';
 }

return $data;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM