我有以下場(chǎng)景:具有多個(gè)航點(diǎn)的數(shù)組想要每個(gè)航點(diǎn)都有一個(gè)新變量航點(diǎn)數(shù)量不固定該數(shù)組存儲(chǔ)路徑點(diǎn)的地址數(shù)據(jù),如街道、號(hào)碼、郵政編碼、城鎮(zhèn)等。我可以在 foreach 循環(huán)中循環(huán)并打印數(shù)組的輸出,如下所示:foreach ($waypoints as $waypoint) { echo $waypoint->street echo $waypoint->nb echo $waypoint->zip echo $waypoint->town}我想做的是,為每個(gè)航路點(diǎn)獲取一個(gè)新變量。例如:$wp1 = Data from waypoint 1$wp2 = Data from waypoint 2我嘗試過的:$waypointCount = count($waypoints); for ($i = 1; $i < $waypointCount; $i++) { $wp[$i] = $waypoints->street.' '.$waypoints->nb.' '.$waypoints->zip.' '.$waypoints->town.' '.$waypoints->state;}我的想法是計(jì)算航點(diǎn)的數(shù)量,為每個(gè)航點(diǎn)編號(hào)設(shè)置一個(gè)新變量,并將相應(yīng)的航點(diǎn)數(shù)據(jù)存儲(chǔ)在新變量中。我有點(diǎn)困惑如何創(chuàng)建 $wp[i] 變量并向其分配數(shù)據(jù)。是否需要結(jié)合 for 和 foreach 循環(huán)?尋求一些幫助讓我走上正確的方向。謝謝!
1 回答

慕容3067478
TA貢獻(xiàn)1773條經(jīng)驗(yàn) 獲得超3個(gè)贊
看來您需要$waypoints在循環(huán)中訪問數(shù)組的正確索引。另外,請(qǐng)確保您以以下方式開始循環(huán),$i = 0否則您將跳過第一個(gè)元素。
$waypointCount = count($waypoints);
for ($i = 0; $i < $waypointCount; $i++) {
$wp[$i] = $waypoints[$i]->street.' '.$waypoints[$i]->nb.' '.$waypoints[$i]->zip.' '.$waypoints[$i]->town.' '.$waypoints[$i]->state;
}
- 1 回答
- 0 關(guān)注
- 119 瀏覽
添加回答
舉報(bào)
0/150
提交
取消