0

I am still pretty new at PHP and looking for some advice/help please.

Ok so to set the scene, I have two tables:

Table 1 which is for a list of companies, and the only field of interest in this situation is

WorkActivities

. This field is a lookup from another table, which contains a list of work activities and their associated risk (low, medium, high):

SELECT
    SubcontractorWorkActivityPk,
    SubcontractorTypeFk,
    SubcontractorWorkActivity,
    RiskRating
FROM dbo.Lookups_SubcontractorWorkActivities

I have set the WorkActivities field in the companies table to be a multi select dropbox, so it can contain multiple values in an array.

It is possible so select numerous activities, each having their own risk.

On the risk, it runs in order of primary key auto number, so 1 - low, 2=medium, 3=high.

What I am trying to achieve is for the following code to look up the value in WorkActivities, and then determine the max value from primary key, hence ensuring that if a product is selected with low, low, medium and high risk, the database will identify the highest risk, which i will then use later.

The code I have so far is:

if($values['WorkActivities'])
{
    $array1 = explode(',',$values['WorkActivities']);
    echo "Array 1 = ".$array1."<BR>";

    foreach ($array1 as $item)
        {
            $rstmp10 = CustomQuery("select * FROM dbo.Lookups_SubcontractorWorkActivities WHERE SubcontractorWorkActivityPk='$item'");
            $datatmp10 = db_fetch_array($rstmp10); 
            echo "Individual Risk Rating : ".$datatmp10["RiskRating"]."<BR>";
        }
            echo "Max Risk Rating : ".max($datatmp10["RiskRating"]);
}

This successfully fetches the risk rating primary key and loops them through, as seen by the echo below (Individual Risk Rating), but it fails when trying to find the max, I suspect its because i havent set this as an array, but honestly dont know... The result of echos is:

Array 1 = Array Individual Risk Rating : 1 Individual Risk Rating : 2 Individual Risk Rating : 4

Fatal error: Uncaught TypeError: max(): Argument #1 ($value) must be of type array, float given in C:\

Any assistance would be much appreciated, thank you.

  • I think you could use a `join` and some ordering option to get only the highest risk from each `group`ing. Looks like `WorkActivities` is a CSV though? If so you should restructure that before this becomes a larger issue (see https://stackoverflow.com/questions/3653462/is-storing-a-delimited-list-in-a-database-column-really-that-bad)...Also values should be bound, not placed directly into query, this leads to SQL injections. – user3783243 Jun 22 '22 at 11:25
  • Does this answer your question: https://stackoverflow.com/questions/31631991/get-highest-value-from-associative-array-foreach – bloodyKnuckles Jun 22 '22 at 11:37

0 Answers0