我想在关联数组中插入两个值,一个用于键,第二个用于值,因为我打印该数组时,它应包含所有a-k作为键,0-10作为其对应值。
<?php
$z=array("a","b","c","d","e","f","g","h","i","j","k");
$countsub1 = array();
for($i=0;$i<=10;$i++)
{
$countsub1 = array("$z[$i]","$i");
}
print_r($countsub1);
?>
在这里,我只得到数组中变量的最后一个值,但我希望所有变量都在一个中。如何做到这一点??
我想要输出
数组([a] =&gt; 0,[b] =&gt; 1,[c] =&gt; 2,[d] =&gt; 3,[e] =&gt; 4,[f] =&gt; ; 5 ..........等等)
答案 0 :(得分:2)
在一行中,您可以使用 array_flip() PHP函数。
$countsub1 = array_flip($z);
OR
$z=array("a","b","c","d","e","f","g","h","i","j","k");
$countsub1 = array();
for($i=0;$i<=10;$i++)
{
$countsub1[$z[$i]] = $i;
}
print_r($countsub1);
<强>输出强>
Array
(
[a] => 0
[b] => 1
[c] => 2
[d] => 3
[e] => 4
[f] => 5
[g] => 6
[h] => 7
[i] => 8
[j] => 9
[k] => 10
)
答案 1 :(得分:0)
您没有将其存储到array
。您将其存储到variable
。这就是为什么它覆盖了最后一个值而你正在获得最后一个值。试试 -
$countsub1[] = array("$z[$i]","$i");
答案 2 :(得分:0)
试试这个:
<?php
$z=array("a","b","c","d","e","f","g","h","i","j","k");
$countsub1 = array();
for($i=0;$i<=10;$i++) {
$countsub1[] = array($z[$i],$i);
}
print_r($countsub1);
?>
您必须将赋值给$countsub1[]
的数组,因为$countsub1
将覆盖每个循环上的前一个值。
PS:变量不应该像分配时一样放在引号内,PHP可能会将其视为字符串
答案 3 :(得分:0)
您继续覆盖$countsub1
,这就是您只获得最后一个值的原因。
您需要使用以下方法之一将其附加到数组中:
$countsub1[] = array("$z[$i]","$i");
array_push($countsub1, array("$z[$i]","$i"));
答案 4 :(得分:0)
制作像OP这样的关联数组的答案是: 如果您想要重复密钥,下面的代码将起作用,如果不是,我建议进行数组合并
$z=array("a","b","c","d","e","f","g","h","i","j","k");
$countsub1 = array();
for($i=0;$i<=10;$i++)
{
//duplicate keys option
$countsub1[] = array($z[$i] => $i);
//single array with unique keys
$countsub1 = array_merge($countsub1, array($z[$i] => $i));
}
print_r($countsub1);
答案 5 :(得分:0)
试试这个:
$arr=array();
for($i=0; $i<=10; $i++){
$key =$z[i];
$arr[$key]=$i;
}
答案 6 :(得分:-1)
像其他人说的那样,你继续分配给$countsub1
,所以它被覆盖并具有最后一个赋值的值。您需要追加代替。
所以你要做的是翻转$z
数组的键和值,对吧?如果是这样,那么您已经有了预定义的功能:array_flip
编辑:如果你想手动完成,我建议下面更灵活的代码,接受不同长度的$z
:
$countsub1 = array();
foreach ($z as $key => $value) {
$counsub1[$value] = $key;
}
答案 7 :(得分:-2)
在您的代码中,如果要将值插入数组,则将值分配给变量hens,它将获取最后一个值
$array=array()
for($i=0;$i<=10;$i++)
{
$array[] = array($z[$i],$i);
}
print_r($array)
$array[] is the method to insert values into the array.and $array is the method to assign value to variable .
that's the reason you are getting only last value as it is overwriting the previous value.
$array[] will store the values into the index like "0,1,2....."
$array will override the values every time in the loop
if you use $array['key'] in the loop it will also do the same job as $array