我已经搞砸了我的php,只是想要一些帮助。目前,我的代码采用从下拉框中选择的值,并将值及其对应的行放在表格中,放入3D数组中。但是,它只需要是一个2D阵列,但我不知道如何摆脱3D阵列的第一个维度。 Php代码:
<?php
function startmatching(){
define( "DB_DSN", "mysql:host=localhost;dbname=FoodMatching");
define( "DB_USERNAME", "root");
define( "DB_PASSWORD", "" );
// define the empty array to be filled from db
$results = array();
// any other php tasks that dont needthe ingcats
// store sql
$IngName = $_POST['IngredientName'];
$IngCounter=0;
while($IngCounter<count($IngName)){
$sSQL = "SELECT IngID, IngName, Texture, Colour, Bitter, Sweet, Sour, Salty, Umami FROM IngredientCharacteristics WHERE IngName='$IngName[$IngCounter]'";
// create an instance of the connection
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
// prepare
$st = $conn->prepare( $sSQL );
// execute the connection
$st->execute();
$counter=0;
// while myslq has rows loop over them and store
while($row = $st->fetch() ){
$results[$counter][] = $row;
$counter++;
}
$IngCounter++;
}
print_r($results);
}
?>
HTML:
<form method='post' role="form" autocomplete="off">
<div class="entry input-group col-xs-3">
<?php //this function takes the ing id and ingname from ingredientcharacteristics table.
// if there are results stored create the select and loop over
if(!empty($aIngList)){
echo "<span class='form-control' style = 'float:left; font-size: 20px;font-family:'Helvetica Neue' ><select name = 'IngredientName[]' class = 'custom-dropdown__select custom-dropdown__select--white'>";
//class = 'custom-dropdown custom-dropdown--white'
echo "<option value='' default >Choose an Ingredient</option>";
foreach ($aIngList as $iIngID => $sIngName) {
echo "<option value='".$sIngName."' >".$sIngName."</option>";
}
echo "</select></span>";
}else{
echo "<p>No results available!</p>";
}
?>
<span class="input-group-btn">
<button class="btn btn-success btn-add" type="button">
<span class="glyphicon glyphicon-plus"></span>
</button>
<button type="submit" class="hidden" name="startmatch" value ="startmatch" id="submit-form"></button>
</span>
</div>
</form>
输出$ results给出以下内容:
Array
(
[0] => Array
(
[0] => Array
(
[IngID] => 2
[0] => 2
[IngName] => Apples Fresh
[1] => Apples Fresh
[Texture] => 4
[2] => 4
[Colour] => 8
[3] => 8
[Bitter] => 7
[4] => 7
[Sweet] => 3
[5] => 3
[Sour] => 4
[6] => 4
[Salty] => 8
[7] => 8
[Umami] => 9
[8] => 9
)
[1] => Array
(
[IngID] => 2
[0] => 2
[IngName] => Apples Fresh
[1] => Apples Fresh
[Texture] => 4
[2] => 4
[Colour] => 8
[3] => 8
[Bitter] => 7
[4] => 7
[Sweet] => 3
[5] => 3
[Sour] => 4
[6] => 4
[Salty] => 8
[7] => 8
[Umami] => 9
[8] => 9
)
)
)
我不知道如何摆脱额外阵列,所以任何帮助都会受到赞赏:)
答案 0 :(得分:0)
问题在于这一行:
$results[$counter][] = $row;
解决方案是将其更改为
$results[] = $row;
PHP会自动将$row
附加到$results
,这意味着您根本不需要$counter
变量。