简体   繁体   English

如何version_compare PHP中的每个数组值?

[英]how to version_compare each array value in php?

I have two arrays I need to compare with the operator <= . 我有两个数组需要与运算符<=进行比较。 I thought an easy way to try and do this is using version_compare but I'm not sure that A. This is best method and B. It's actually comparing the right values. 我以为可以尝试执行此操作的简便方法是使用version_compare但我不确定A。这是最好的方法,而B。实际上是在比较正确的值。

In order for version_compare to work I implode the array. 为了使version_compare起作用,我将数组内爆。

//Original arrays.

a$ = array( 0 => "ajax dropdown0.1.5", 1 => "hello dolly1.6", 2 => "test4.5");
b$ = array( 0 => "ajax dropdown0.1.4", 1 => "hello dolly1.6", 2 => "test4.6");

//implode into string

$a_implode = implode( "," , $a );
$b_implode = implode( "," , $b );

//compare version

if (version_compare($a_implode, $b_implode, '<=')){
                    echo 'We have a problem';
                    }

This seems to work but I have no idea if it's actually comparing the correct values, for instance test4.5 must only be compared to test4.6 ( and not the other string values), also I am unsure how to output any matches if version_compare returns true. 这似乎可行,但我不知道它是否实际上在比较正确的值,例如,test4.5仅必须与test4.6(而不是其他字符串值)进行比较,而且我不确定如果version_compare如何输出任何匹配项返回true。

    foreach( array_keys( $a ) AS $key ) {            
        if( version_compare($a[$key], $b[$key], '<=')) { print "we have a problem with: " . $a[$key] . "\n"; }
    }

I have made a simple Class for you to solve your problem as easy as its posibble. 我为您准备了一个简单的类,以解决您的问题,就像它的坡道一样容易。

the Class file (class.myversion.php) 类文件(class.myversion.php)

<?php
class MyVersion
{
    private $_version;
    private $_name;

    public function __construct($_name, $_version)
    {
        $this->_version = $_version;
        $this->_name = $_name;
    }
    public function getVersion()
    {
        return $this->_version;
    }
    public function getName()
    {
        return $this->_name;
    }
}
?>

And the Test File (test.php) 和测试文件(test.php)

require 'class.myversion.php';

$a = Array();
$b = Array();

$a[] = new MyVersion("ajax dropdown", 15); // 15 means 0.1.5
$a[] = new MyVersion("hello dolly", 16);
$a[] = new MyVersion("test", 45);

$b[] = new MyVersion("ajax dropdown", 14); // 14 means 0.1.4
$b[] = new MyVersion("hello dolly", 16);
$b[] = new MyVersion("test", 46);

for($i = 0; $i < sizeof($a); $i++)
    if($a[$i]->getVersion() < $b[$i]->getVersion())
        echo "(".$a[$i]->getName().")needs to get Updated. Required version: ".$b[$i]->getVersion()."<br />";
    elseif($a[$i]->getVersion() > $b[$i]->getVersion())
        echo "(".$b[$i]->getName().")needs to get Updated. Required version: ".$a[$i]->getVersion()."<br />";
?>

Thats it! 而已! If you think its hard to understand, i can explain it but i think its easy enought to understand. 如果您认为它很难理解,我可以解释一下,但是我认为它很容易理解。

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

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