简体   繁体   English

如何乘以php数组的元素

[英]How to multiply elements of php array

I'm trying to translate a javascript function into php but having some problems with my arrays. 我正在尝试将javascript函数转换为php,但是数组存在一些问题。 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; 可以肯定是因为我的语法$ 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_coordinate += 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. 它应该使用$ i而不是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 更深入-将$放在变量前面,将while循环更改为foreach,将print更改为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. 它们将每次运行,但是如果您执行while循环,则实际上并不会使用php。 For a more extreme example, post code with lots of while loops up with a "python" tag and ask if it can be simplified. 举一个更极端的例子,带有很多while的邮政编码循环带有“ python”标签,并询问是否可以简化它。

foreach loops and echo are idiomatic php, while loops and print only works. foreach循环和echo是惯用的php,而循环和print仅适用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM