Skip to content
Advertisement

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. 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++;
        }

Advertisement

Answer

I tried to debug your code though.The problem is that you try to access element [0] of $moduleF. You should change $moduleF[$j][‘Module’] to $moduleF[‘Module’].

Use standard functions where possible. for finding values within (multidimensional) array’s you can use array_search. The code beneath works.

Also don’t compare strings with == use strcmp(str1, str2) == 0 instead

        $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);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement