1

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"
  }
4
  • please post the $inventory data.. it is not clear which kind of fields you store there and how your data looks like Commented Nov 27, 2014 at 0:31
  • The only data from $inventory that is relevant is the name value $invName which is being pulled at the top of the foreach(). I basically just need to keep track of the amount of occurrences so that I can display it as say "2x Inventory Name Here" Commented Nov 27, 2014 at 0:33
  • i think you are doing it wrong because you probably have multiple items which need different counts.. you are missing at least one loop.. but without some sample data it hard to figure it out for sure Commented Nov 27, 2014 at 0:37
  • just add another index which holds the quantity, thats the value you'd want to increment Commented Nov 27, 2014 at 1:46

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.