我试图将一组新的键和值添加到二维关联数组中。这是我的数组
myArray = array(1 => array("John", 500, "2012-09-02"),
2 => array("Mike", 105, "2012-07-01"),
3 => array("Joe", 24, "2011-12-23"),
4 => array("Alex", 65, "2012-08-30"));
我想要做的是让用户输入一个ID和一个名称,如果他们输入的数据在myArray中,则增加值[1]为5,但是如果它不是我想要添加他们的信息作为新数据进入数组,因此它应输出/打印第5个$ key和$ values。 if语句工作正常,并将值5添加到[1],但我似乎无法使用else if语句添加新条目。
$nameExists = FALSE;
$name = htmlspecialchars($_POST['name']);
$id = htmlspecialchars($_POST['id']);
foreach($myArray as $key => $value){
if($key == $id && $value[0] == $name){
$value[1] = $value[1] + 5;
$nameExists = TRUE;
}
else if ($nameExists === FALSE){
$newData = array($name, 1, date("Y-m-d"));
$myArray[] = $newData;
}
echo "<tr><td>".$key."</td>
<td>".$value[0]."</td>
<td>".$value[1]."</td>
<td>".$value[2]."</td></tr>";
}
任何帮助表示感谢,谢谢。
答案 0 :(得分:0)
对$nameExists === FALSE
的检查看起来有一个逻辑流问题。这应该在整个foreach
循环完成之后进行测试,而不是在循环体内。否则,循环测试第一个数组元素是否匹配,如果没有找到,则继续追加到数组。
而是将$nameExists === FALSE
移到循环之后。如果未找到匹配项,则该标志将不会设置为TRUE
,并且数组追加应该有效。
$nameExists = FALSE;
// Note: use htmlspecialchars() on *output to HTML* not on input filtering!
// If you print these values later in the page, you should enclose them
// in htmlspecialchars() at that time. Placing it here may cause
// your values not to match in the loop if the stored vals were unescaped.
$name = $_POST['name'];
$id = $_POST['id'];
// Note the &$value is needed here to modify the array inside the loop by reference
// If left out, you'll get through the loop and changes will be discarded.
foreach($myArray as $key => &$value){
if($key == $id && $value[0] == $name){
$value[1] = $value[1] + 5;
$nameExists = TRUE;
// No need to continue looping, you can exit the loop now
break;
}
// Finish loop - flag was set TRUE if any match was found
}
// Now, if nothing was modified in the loop and the flag is still FALSE, append a new one
if ($nameExists === FALSE){
$newData = array($name, 1, date("Y-m-d"));
$myArray[] = $newData;
}
// Use a separate loop to output your complete array after modification
foreach ($myArray as $key => $value) {
// use htmlspecialchars() here instead...
// And display output values indexed $myArray[$id]
echo "<tr><td>".$key."</td>
<td>".htmlspecialchars($value[0])."</td>
<td>".htmlspecialchars($value[1])."</td>
<td>".htmlspecialchars($value[2])."</td></tr>";
}
检查the PHP foreach
documentation中有关使用&
引用修改循环数组的注释。