-1

I'm getting an error. Undefined Index when trying to call $distance[$newkey] (one UI error for each combination of keys). What am I doing wrong? Keep in mind I'm new to programming, so keep it very simple. I won't understand jargon. Thanks.

<?php

Require_once 'Work-Cell-Scheduler/WCS/os.php';

$NumSuppliers=5;
$NumDepts=5;

//capacity
$capacity=array();
for($i=0;$i<$NumSuppliers;$i++){
    $capacity["S{$i}"]=rand(400,600);
}
$totalcapacity=array_sum($capacity);
//print_r($capacity);
$demand=array();
for($i=0;$i<$NumDepts;$i++){
    $demand["D{$i}"]=rand(300,550);
}
$totaldemand=array_sum($demand);
//print_r($demand);

if($totaldemand>$totalcapacity){
    echo "random problem is infeasible";
}
$profit=array();
foreach($demand as $key => $value){
    $profit[$key]=rand(20,40);  
}
//print_r($profit);

$distance=array();
foreach($profit as $key => $value){
    foreach($capacity as $k => $v){
        $newkey = "{$key},{$k}";
        $distance[$newkey]=rand(1,9);
    }
}
//print_r($distance);

//total profit = profit - cost of transportation (distance)
$tprofit=array();
foreach($capacity as $key => $value){
    foreach($profit as $k => $v){
        $newkey="${key},${k}";
        print_r($distance[$newkey]);
        $tprofit[$newkey]= $v - $distance[$newkey];
    }
}
//print_r($tprofit);

2 Answers2

0

The problem is line:

$tprofit[$newkey]= $v - $distance[$newkey];

You make calculation but variable

$distance[$newkey]

is not set.

You should check if $distance[$newkey] is set using:

if (isset($distance[$newkey])) {
  // .. one task
}
else {
 // .. another task
}

In your case it should probably be:

if (isset($distance[$newkey])) {
  $tprofit[$newkey]= $v - $distance[$newkey];
}
else {
 $tprofit[$newkey]= $v;
}
Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
  • This code removes the error; however, the output for $tprofit = $profit (looped about 5 times though) so if $profit=(1,2,3), $tprofit=(1,2,3,1,2,3,...1,2,3). How can I make this subtraction work? could I put the code that creates the $distance array within the loop? – user3609746 May 10 '14 at 18:31
  • You should simple think about your application logic – Marcin Nabiałek May 10 '14 at 18:49
0

In your last foreach loop,

$tprofit=array();
foreach($capacity as $key => $value){
    foreach($profit as $k => $v){
        $newkey="${key},${k}";
        print_r($distance[$newkey]);
        $tprofit[$newkey]= $v - $distance[$newkey];
    }
}

The correct one is :

$tprofit=array();
foreach($capacity as $key => $value){
    foreach($profit as $k => $v){
        $newkey="{$key},{$k}";
        print_r($distance[$newkey]);
        $tprofit[$newkey]= $v - $distance[$newkey];
    }
}

You were assigning wrong string to $newkey. Try it now, and update your question if more errors pop up.

Abhishek Goyal
  • 867
  • 1
  • 7
  • 21