php从Array中减去变量

时间:2015-02-12 20:22:17

标签: php arrays subtraction

我正在定义减法变量:

    $query = "
    SELECT * FROM around WHERE `long` != '' ORDER BY id DESC"; 
    $result = mysql_query( $query );

    $select_maxlong = mysql_query("SELECT long FROM around WHERE
    `id`='$max_id'");
    $row3 = mysql_fetch_row($select_maxlong);
    $max_long = $row3[0];

然后我需要从下面的数组值中减去$ max_long:

   while ( $row = mysql_fetch_assoc( $result ) ) {

   echo $row['long'];}

我试过了:

   foreach($row as $row) {
   $car = $max_long;
   echo "u";
   echo $car - $row['long'] ; }

但输出不正确。

如果数组中有10个数字,$ row ['long'],我想从每个数字中减去$ max_long,并回显结果。

1 个答案:

答案 0 :(得分:1)

此代码应该适合您

$select_maxlong = mysql_query("SELECT long FROM around WHERE `id`='$max_id'");
$row3 = mysql_fetch_row($select_maxlong);
$max_long = $row3[0];

$myarray=array();
while ( $row = mysql_fetch_assoc( $result ) ) {
   $myarray[]=$row['long'];
}

function showvalue($element, $key) {
  echo $max_long-$element;
}

array_walk($myarray,'showvalue');

但是这样,你正在减去$ max_long中的元素,而不是像你说的那样(那是你的代码似乎尝试的东西)。如果你想真正从数组的每个元素中减去$ max_long并输出结果,只需在echo线上反转变量顺序。希望这会有所帮助。