使用相同索引在同一数组中存储多个值

时间:2015-10-08 05:30:26

标签: php arrays

如果我想在 PHP 中具有相同索引的数组中添加多个值,那么是否可以创建这种类型的数组?例如,

fruits[a]="apple";
fruits[a]="banana";
fruits[a]="cherry";
fruits[b]="pineapple";
fruits[b]="grappes";

我希望数组如下所示: -

fruits = {[a]=>"apple",[a]=>"banana",[a]=>"cherry",[b]=>"pineapple",[b]=>"grappes"};

3 个答案:

答案 0 :(得分:4)

您无法在相同的键或索引下定义多个值。 在你的情况下 -

fruits[a]="apple";
fruits[a]="banana";

此处apple将替换为banana

相反,您可以将数组定义为 -

fruits[a][] = "apple";
fruits[a][] = "banana";

答案 1 :(得分:1)

编辑:我用PHP代码更新了我的答案,但我通常不编码php,这可能不是最优的解决方案,我在php沙箱中尝试了这段代码

$subarray1[0] = "apple";
$subarray1[1] = "banana";
$subarray1[2] = "cherry";

$subarray2[0] = "pineapple";
$subarray2[1] = "grappes";

$fruits[0] = $subarray1;
$fruits[1] = $subarray2;

foreach( $fruits as $key => $value ){
    foreach( $value as $key2 => $value2 ){
        echo $key2."\t=>\t".$value2."\n";
    }
}

答案 2 :(得分:0)

使用内爆并爆炸。

subarray1[0] = "apple"
subarray1[1] = "banana"
subarray1[2] = "cherry"

subarray2[0] = "pineapple"
subarray2[1] = "grappes"

商店数据是,(逗号)

$ar="";
for($i=0;$i<=count(subarray1);$i++)
{
$ar[]=subarray1[$i];
}
$rt=implode(',',$ar);
 echo $rt;

删除,(逗号)表格数组

$ex=explode(",",$ar);
print_r($ex);