PHP检查哪个数组有更大的值

时间:2016-11-23 18:01:42

标签: php arrays

好的,所以我试图比较哪个数组有更大的值,但我希望这个代码更短,而不是运行两个foreach循环。

$one = array("test", "100");
$two = array("something", "200");

$distance1;
$distance2;

foreach($one as $val => $key) {
    $distance1 =  $val;
}

foreach($two as $val => $key) {
    $distance2 =  $val;
}

if($distance1 > $distance2)

2 个答案:

答案 0 :(得分:0)

我不完全确定你想做什么,自从我上次写PHP以来已经有一段时间了,但我喜欢这个问题,我想建议4种可能的方法:

1:使用你提供的阵列(我相信这可能是你的意思)

$one = array("test", "100");
$two = array("something", "200");

$distance1 = $one[1];
$distance2 = $two[1];

if($distance1 > $distance2)

2:关联数组和值

的数字
$one = array(
    "name" = > "test", 
    "distance" => 100
);
$two = array(
    "name" => "something", 
    "distance" => 200
);

if ($one["distance"] > $two["distance"])

3:使用带$ key和$ val的foreach循环

$distances = array(
    "test" => 100,
    "something" => 200
);
$highestDistance = 0;
$highest = null;

foreach ($distances as $key => $val) {
    if ($val >= highestDistance) {
        $highestDistance = $val;
        $highest = $key;
    }
}

if ($highest === 'test')

4:对象和排序:

$distances = array(
    (object) array(
        "name" => "test", 
        "distance" => 100
    ),
    (object) array(
        "name" => "something", 
        "distance" => 200
    )
);

usort($distances, function($a, $b) { return $a - $b; });

if ($distances[0]->name === 'test')

请注意,最终if语句的条件评估为false,因为我认为是您的意图(因为100不超过200)。

答案 1 :(得分:-2)

您可以组合2个阵列

<?php
    $one = array("test", "100");
    $two = array("something", "200");
    $result = array_merge($one , $two);
    foreach($result as $val => $key) {
       echo $val;
    }
    ?>