我有一个应用程序,通过一个CSV条目记录月份和年份,即db列命名为answer1
是jan,2008
和列answer2
是feb,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
};
};
?>
我希望在文档后面的另一个php块中出现类似的内容。
<?php echo '<div id=" '.$colName[answer2] . $myArray[0] . ' ">test</div> ';?>
这可能容易得多。在进入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'];