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.
In order for version_compare to work I implode the array.
//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.
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)
<?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)
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.
精彩评论