简体   繁体   English

php 数组:如果键值相同,则选择其他键值最高的

[英]php array: if identical key values then choose highest by other key value

$myArray = [
    "ID" => "",
    "Module" => "",
    "Version"=> ""
];

Output:
[
{23,finance,1.0},
{24,finance,1.1},
{25,logistic,1.0}
]

I have an array with the given Keys like above.我有一个带有上述给定键的数组。 I need a new array that gives me the highest Version IF module is same.我需要一个新数组,它给我最高版本的 IF 模块是相同的。 How would I do that?我该怎么做?

desired Output:
[
{24,finance,1.1},
{25,logistic,1.0}
]

This is what I tried这是我试过的

        $modulesFiltered = [];
        $i = 0;
        $j = 0;
        foreach($modules as $module){
          $modulesFiltered[$i]['ID'] = $module['ID'];

          foreach($modulesFiltered as $moduleF){
            if(!empty($moduleF[$j]['Module'])){
              if($module[$i]['Module'] == $moduleF[$j]['Module']){
                $modulesFiltered[$i]['Module'] = 'this is doubled';
              }
            } else {
              $modulesFiltered[$i]['Module'] = $module['Module'];
            }
            $j++;
          }

          $modulesFiltered[$i]['Module'] = $module['Module'];
          $i++;
        }

I tried to debug your code though.The problem is that you try to access element [0] of $moduleF.我试图调试你的代码。问题是你试图访问 $moduleF 的元素 [0]。 You should change $moduleF[$j]['Module'] to $moduleF['Module'].您应该将 $moduleF[$j]['Module'] 更改为 $moduleF['Module']。

Use standard functions where possible.尽可能使用标准函数。 for finding values within (multidimensional) array's you can use array_search .要在(多维)数组中查找值,您可以使用array_search The code beneath works.下面的代码有效。

Also don't compare strings with == use strcmp(str1, str2) == 0 instead也不要将字符串与 == 进行比较而是使用 strcmp(str1, str2) == 0

        $inputArray = array(
        array(
            "ID" => 23,
            "Module" => "finance",
            "Version"=> 1.0),
        array(
            "ID" => 24,
            "Module" => "finance",
            "Version"=> 1.1),
        array(
            "ID" => 25,
            "Module" => "logistiscs",
            "Version"=> 1.0));



    $output = array();


    foreach($inputArray as $element)
    {
        $key = array_search($element["Module"], array_column($output, "Module"));
        
        if(is_numeric($key))
            $output[$key]["Version"] = max($element["Version"], $output[$key]["Version"]);
        
        else
            $output[] = $element;
        
    }

    print_r($output);

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

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