سؤال

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);
هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top