选择性循环通过if和foreach的多维数组?

时间:2014-02-03 15:33:01

标签: php multidimensional-array foreach

我有一个用于计算的二维数组。我如何遍历它,以便我可以只针对具有相同索引的元素检查我的IF子句。

我认为应该用foreach来完成,但我无法使它工作。 我想检查IF子句对$ array [1] [0],$ array [2] [0],$ array [3] [0] ......等等

非常感谢您的帮助!

<?php

//variables

$variable1 = 50;
$variable2 = 100;

$array = array( array(50, 125 , 15),
                array(30, 75 , 25),
                array(50, 25 , 7) 
             );
echo "<pre>";
print_r($array);
echo "<pre>";

if ($variable1 > $array[0][0]) {
    $reserve[] = $variable1 - $array[0][0];
    $surplus[] = 0;
} elseif ($variable1 == $array[0][0]) {

    $reserve[] = 0;
    $surplus[] = 0;
} 
 else {
    $surplus[] = $array[0][0] - $variable1;
    $reserve[] = 0;

}

echo "<pre>";
print $reserve[0];
echo "<pre>";

echo "<pre>";
print $surplus[0];
echo "<pre>";

?>

这是完整的代码,基于部分解决方案。任何想法为什么它没有工作?我在foreach行中遇到错误。

<?php
error_reporting(E_ALL);
$con=mysqli_connect("localhost","root","","base1");
// Check connection
if (mysqli_connect_errno($con))
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$sql="SELECT * FROM details";
$result=mysqli_query($con,$sql);


while ($data = mysqli_fetch_array($result, MYSQLI_NUM)) {

    /////////////////////

    }
    // Free result set
mysqli_free_result($result);

mysqli_close($con);
/////////////////////////////////////////////
?><?php


$variable1= 50;


$reserve = array();
$surplus = array();
foreach($data as $key=>$next)
{
   if ($variable1> $array[$key][0])
   {
      $reserve[] = $variable1- $array[$key][0];
      $surplus[] = 0;
   }
   elseif($variable1== $array[$key][0])
   {

      $reserve[] = 0;
      $surplus[] = 0;
   } 
   else 
   {
      $surplus[] = $array[$key][0] - $variable1;
      $reserve[] = 0;
   }
}

echo "<pre>";
print_r($reserve);
echo "<pre>";

echo "<pre>";
print_r($surplus);
echo "<pre>";

?>

2 个答案:

答案 0 :(得分:0)

我可能在这里完全错了。尝试这样的事情:

//variables

$variable1 = 50;
$variable2 = 100;

$array = array( array(50, 125 , 15),
            array(30, 75 , 25),
            array(50, 25 , 7) 
         );

echo "<pre>";
print_r($array);
echo "<pre>";

foreach($array as $key=>$next)
{
   if ($variable1 > $array[$key][0])
   {
      $reserve[] = $variable1 - $array[$key][0];
      $surplus[] = 0;
   }
   elseif($variable1 == $array[$key][0])
   {

      $reserve[] = 0;
      $surplus[] = 0;
   } 
   else 
   {
      $surplus[] = $array[$key][0] - $variable1;
      $reserve[] = 0;
   }
}

echo "<pre>";
print_r($reserve);
echo "<pre>";

echo "<pre>";
print_r($surplus);
echo "<pre>";

答案 1 :(得分:0)

我尝试过foreach并且有效:

foreach ($array as $subarray) {

    if ($variable1 > $subarray[0]) {
        $reserve[] = $variable1 - $subarray[0];
        $surplus[] = 0;
    } elseif ($variable1 == $subarray[0]) {

        $reserve[] = 0;
        $surplus[] = 0;
    } else {
        $surplus[] = $subarray[0] - $variable1;
        $reserve[] = 0;
    }
}