在foreach循环之外调用PHP多维数组

时间:2013-05-24 20:06:01

标签: php arrays multidimensional-array

我有一个应用程序,通过一个CSV条目记录数月和数年,即名为answer1的数据库列为jan,2008,列answer2feb,2013。我想在html中使用特定月份(jan),但它只给我最后一个数组数据。

<?php
foreach ($row as $colName => $colValue )
  {
  if($colName === answer1 || $colName === answer2)
    {               
     //break apart date data
     $myArray = explode(',', $colValue);
     echo '<div id=" ' .$colName . $myArray[0] . ' ">test</div> ';//this works
        };
  };

&GT;

我希望稍后在doc中的另一个php块中使用这样的东西。

<?php echo '<div id=" '.$colName[answer2] . $myArray[0] . ' ">test</div> ';?>

1 个答案:

答案 0 :(得分:0)

这可能要容易得多。在我们开始使用PHP之前,我们正在从MySQL的原始列中爆炸(或拉动两个子串)。然后你可以随意使用它们:

$query = "SELECT SUBSTRING_INDEX(answer1,',',1) as a1_month,
SUBSTRING_INDEX(answer1,',',-1) as a1_year,
SUBSTRING_INDEX(answer2,',',1) as a2_month,
SUBSTRING_INDEX(answer2,',',-1) as a2_year from my_table";
$result = mysqli_query($query);


$answers = array();
$x = 0;
while ($row = mysqli_fetch_array($result)){

    $answers[$x]['answer1_year'] = $row['a1_year'];
    $answers[$x]['answer1_month'] = $row['a1_month'];
    $answers[$x]['answer2_year'] = $row['a2_year'];
    $answers[$x]['answer2_month'] = $row['a2_month'];
 $x++;
}

print_r($answers);

如果由于某种原因你仍然需要连接字符串,你可以这样做:

$answer1 = $answers[0]['answer1_month'].','.$answers[0]['answer1_year'];
$answer2 = $answers[0]['answer2_month'].','.$answers[0]['answer2_year'];
相关问题