Using Array Key => Value to track count of items

166 views Asked by At

I basically have a script where I pull a list of machines, then pull all of the inventory currently inside of them. If the machine has more than 1 of the same type of inventory (drives for example) then my current code just appends them into a long string which looks rather poor.

I would instead like to save the inventory into arrays and keep track of the amount assigned. I am using array_key_exists() to determine if that type has already been added to the array.

My problem is how can I store the count and increment it each time another one is found, then when I append it to another array, rewrite it such as "4x 1TB Hard-Drive", "2x 240GB SSD Drive"? Right now it is added as "1TB Hard-Drive1TB Hard-Drive1TB Hard-Drive1TB Hard-Drive".

Pseudo-Code:

<?

$row = array();
$arrDrive = array();

foreach ($inventory as $item)
{
    $invName = getInventoryName($dp_conn, $item["inv_id"]);
    $invType = getInventoryTypeName($item["type_id"], $dp_conn);

    if ($invType == "Hard-Drive")
    {
        if (array_key_exists($invName, $arrDrive))
        {
            $arrDrive[x]++; //???
        }
    }
}

// Get count of each type of drive and reformat it to 2x DRIVE NAME
$display = $arrDrive[count] . "x " . $arrDrive[Name];
array_push($row, $display);

?>

$inventory output as requested

  [1]=>
  array(3) {
    ["inv_id"]=>
    string(2) "16"
    ["type_id"]=>
    string(1) "2"
    ["sort_order"]=>
    string(1) "0"
  }
1

There are 1 answers

0
ymz On BEST ANSWER

instead of using:

if ($invType == "Hard-Drive")
{
    if (array_key_exists($invName, $arrDrive))
    {
        $arrDrive[x]++; //???
    }
}

please use:

if (array_key_exists($item["type_id"], $arrDrive))
{
    $arrDrive[$item["type_id"]]++;
}
else
{
    $arrDrive[$item["type_id"]] = 1;
}

$arrDrive will now have the count for each type in your inventory ($arrDrive is really not a good name in that matter)