0

我有一个看起来大致像这样的 json 文件。

{
   "foo" : {
      "name" : "bar", 
      "dev-master" : {}, 
      "3.0-dev" : {}, 
      "2.4" : {}, 
      "master" : {},
   }
}

我想知道是否有解决方案来解析和获取最重新发送的 semver 标签。我试过了:

<?php 
$file = 'data.json'; 
$content = file_get_contents($file); 
$content = json_decode($content); 

$container = [];
foreach($content as $version){
  $container[$version] = $version; 
}

.. 

现在,假设$container包含所有标签,我如何获得最新版本将是 2.4。

获取2.4不是问题,而是制定一种面向未来的可靠方法来找出哪个是最近的。

4

1 回答 1

1

这是一种方法。它使用最新版本号仅由数字和小数点组成的假设。您可以更新正则表达式以允许破折号等。

#!/usr/bin/php
<?php
$content = json_decode(file_get_contents('data.json'));
$container = [];
foreach($content as $name => $versions){
        $props   = get_object_vars($versions);
        $container[$name] = null;
        foreach (array_keys($props) as $versionName) {
                if (preg_match('/^[0-9\.]+$/',$versionName)) {
                        // Ensure if multiple versions are present the greatest 
value will be used
                        if (isset($container[$name])) {
                            $container[$name] = max($versionName,$container[$nam
e]);
                        } else {
                            $container[$name] = $versionName;
                        }
                }
        }
}
var_dump($container);

如果未找到最终版本,则版本名称将为空。

于 2015-11-13T02:02:54.570 回答