创建数组时未定义的索引

时间:2014-05-10 18:15:28

标签: php arrays indexing undefined

我收到了错误消息。尝试调用$ distance [$ newkey]时的未定义索引(每个键组合有一个UI错误)。 我究竟做错了什么?请记住,我是编程新手,所以请保持简单。我不会理解行话。感谢。

<?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 个答案:

答案 0 :(得分:0)

问题在于:

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

您进行计算但是变量

$distance[$newkey]

未设置。

你应该检查$ distance [$ newkey]是否设置为:

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

在你的情况下,应该是:

if (isset($distance[$newkey])) {
  $tprofit[$newkey]= $v - $distance[$newkey];
}
else {
 $tprofit[$newkey]= $v;
}

答案 1 :(得分:0)

在您的上一个foreach循环中,

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

正确的是:

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

您为$newkey分配了错误的字符串。立即试用,如果弹出更多错误,请更新您的问题。