开发者

How to multiply elements of php array

I'm trying to translate a javascript function into php but having some problems with my arrays. I need to iterate over the array elements, multiplying them all by a certain amount, but it's not changing the values. Pretty sure it's because my syntax $coordinates_p[i][0] *= $scale; isn't correct, but I'm not sure what it should be!

Test code:

<?php

print "Starting.<br/>";

$scale = 100;

$coordinates_p = array();

$i = 0;
$x_coordinate = 1;
$y_coordinate = 2;
while ($i <= 1) {
    $coordinates_p[$i] = array(0 => $x_coordinate, 1 => $y_coordinate);
    $x_co开发者_StackOverflow中文版ordinate += 1;
    $y_coordinate += 2;
    $i++;
}

print "Unscaled: ";
print_r ($coordinates_p);
print "<br/>";

$i = 0;
while (isset($coordinates_p[i])) {
    $coordinates_p[i][0] *= $scale;
    $coordinates_p[i][1] *= $scale;
    $i++;
}

print "Scaled: ";
print_r ($coordinates_p);
print "<br/>";

print "Finished.";

?>


Your code just needs to change from

$coordinates_p[i][0] *= $scale;
$coordinates_p[i][1] *= $scale;

to

$coordinates_p[$i][0] *= $scale;
$coordinates_p[$i][1] *= $scale;


Your error is in

while (isset($coordinates_p[i])) {
    $coordinates_p[i][0] *= $scale;
    $coordinates_p[i][1] *= $scale;
    $i++;
}

it should use $i not i.

like so:

while (isset($coordinates_p[$i])) {
    $coordinates_p[$i][0] *= $scale;
    $coordinates_p[$i][1] *= $scale;
    $i++;
}


Depends on how "deeply" you want to translate

Shallow - put a $ in front of every variable

Deeper - put $ in front of variables, change those while loops to foreach, change print to echo

//before
$i = 0;
while (isset($coordinates_p[i])) {
    $coordinates_p[i][0] *= $scale;
    $coordinates_p[i][1] *= $scale;
    $i++;
}

//Better PHP form
foreach($coordinates_p as $current)
{
   $current[0] *= $scale;
   $current[1] *= $scale;
}

They'll each run, but you're not really USING php if you do those while loops. For a more extreme example, post code with lots of while loops up with a "python" tag and ask if it can be simplified.

foreach loops and echo are idiomatic php, while loops and print only works.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜