给定一个数组。如何使用 foreach
循环迭代
给定数组来创建新数组?
我的尝试:
<?php /* version +7 */
$input = array("teamA", "teamB", "teamC");
foreach ($input as &$value) {
$assign = "50"; /* The data just temp */
$data = array($value => $assign);
}
echo $data["teamA"];
?>
我想你正在寻找这个:
$input = array("teamA","teamB","teamC");
$data = [];
foreach($input as $value){
$assign = "50"; /* The data just temp */
$data[$value] = $assign;
}
echo $data["teamA"];
如果所有键的
$assign
相同:
$data = array_fill_keys($input, 50);
<?php
$input = array("teamA", "teamB", "teamC");
$data = array();
foreach ($input as $value) {
$assign = "50";
$data[$value] = $assign;
}
echo $data["teamA"];
?>
要将新的键值对分配给数组,请使用
$data[$value] = $assign;
请注意,如果数组
$data
已包含该键,则其值将被重新分配给新的值。