我希望只更新我在PHP中创建的关联数组中的[“distanceTimeFromNextPoint”]元素。
我正在尝试更新以下数组结构:
Array
(
[0] => Array
(
[Total time] => 0:00
[0] => Array
(
[place] => Spanish steps
[distanceTimeFromNextPoint] =>
)
[1] => Array
(
[place] => Piazza Venezia
[distanceTimeFromNextPoint] =>
)
)
[1] => Array
(
[Total time] => x0:00
[0] => Array
(
[place] => Piazza Venezia
[distanceTimeFromNextPoint] =>
)
[1] => Array
(
[place] => Spanish steps
[distanceTimeFromNextPoint] =>
)
)
)
但是当我运行此循环时,[“总时间”]元素也会更新! 关于我的循环有什么问题的想法以及如何更改它?
这是我的代码(上面的数组定义为$ new_array):
foreach($new_array as $i=>$element)
{
foreach($element as $j=>$sub_element)
{
$new_array[$i][$j]['distanceTimeFromNextPoint']="x";
}
}
提前谢谢。
答案 0 :(得分:0)
如果我得到了正确的结构,只需添加一个条件,其中您要排除该键并检查该元素是否具有所需的子键,然后进行修订:
foreach($new_array as $i => $element) {
foreach($element as $j => $sub_element) {
if($j !== 'Total time' && array_key_exists('distanceTimeFromNextPoint', $sub_element)) {
$new_array[$i][$j]['distanceTimeFromNextPoint'] = 'x';
}
}
}
答案 1 :(得分:0)
您应该测试元素'distanceTimeFromNextPoint'是否已经存在。
<?php $query_tbl = "SELECT transaksi.id_transaksi, pelanggan.nama FROM transaksi, pelanggan ".
"WHERE transaksi.id_pelanggan = pelanggan.id_pelanggan ORDER BY id_transaksi";
$list_tbl = mysqli_query($dbc, $query_tbl)
or die('Error select table');
while($row = mysqli_fetch_array($list_tbl))
{
echo '<tr>';
echo '<td>' . $row['id_transaksi'] . '</td>';
echo '<td>' . $row['nama'] . '</td>';
?> <!-- here ends the PHP -->
<form method="post" action="pengiriman-input.php">
<input type="hidden" name="id" value="<?php echo $row['id_transaksi']; ?>" />
<input type="submit" value="Kirim" />
</form>
<?php // here begin PHP again
echo '</tr>';
};?>