0

The job to be done is show the price of postage per KG. So starting at 1KG, I want to increase by 0.50 for every KG.

I tried doing it like this which doesn't seem to work for me:

$shipping_second_class = array (
array ('weight' => range(1,5), 'cost' => range(1,3, 0.50))
);

foreach ($shipping_second_class as $shipping_second_class) {
    echo('weight '.$shipping_second_class['weight'].' costs &pound;'.$shipping_second_class['cost'].'<br/>');
}

That doesn't seem to work. What I'm trying to do in a way that's easier to maintain is something like this, but with less code:

$shipping_second_class = array (
    array ('weight' => '1', 'cost' => '1'),
    array ('weight' => '2', 'cost' => '1.5'),
    array ('weight' => '3', 'cost' => '2'),
    array ('weight' => '4', 'cost' => '2.5'),
    array ('weight' => '5', 'cost' => '3'),
);

foreach ($shipping_second_class as $shipping_second_class) {
    echo('weight '.$shipping_second_class['weight'].' costs &pound;'.$shipping_second_class['cost'].'<br/>');
}

3 Answers 3

1

Another simple way

$per_kg_extra_cost = 0.5;
foreach (range(0, 4) as $shipping) {
    $cost = 1 + ( $shipping * $per_kg_extra_cost ); 
    $weight = ++$shipping; 
    echo '<pre>';
    echo 'Weight: '. $weight . '   cost : ' .$cost;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Here's one way to do this:

$shipping_second_class = array (
array ('weight' => 1, 'cost' => 1)
);

for($x = 2; $x < 6; $x++){
    $newdata = ['weight' => $x, 'cost' => 0.5 + $x * 0.5];
    array_push($shipping_second_class, $newdata);
}

foreach ($shipping_second_class as $s) {
    echo('weight '.$s['weight'].' costs &pound;'.$s['cost'].'<br/>');
}

Essentially, you need to add to the array after it's been called rather than initialize it fully filled. You start with the array at 1 value (you could modify this code to start with an empty array) and it expands from there. If you need to add more to the array, just increase the 6 to (Desired Number) + 1 in the for loop.

I'm not sure if there is a way to add to the array in the manner you do in the first block of code.

1 Comment

Just a note, this isn't the perfect way to write it, I would suggest improving it to fit your use.
1

Here is a simple way to do it:

$key = -1;
$interval = 0.5;
$shipping_second_class = array_map(function($v) use (&$key,$interval) {
 $key++;
 return ["weight"=>$v,"cost"=>(1 + ($interval * $key))];                              
},range(1,5));

echo json_encode($shipping_second_class);

You can change the $interval variable if you need to change the way it increments cost

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.