如何更改数组php中的变量名


How to change variable names inside array php

好吧,我已经为此挣扎了好几个小时了,我似乎不知道该怎么做。我有一个数组,里面放了很多百分比值,我正在打印出其中的前5个。$percent变量是通过类似的文本获取的

$array=array($percent12, $percent13, $percent14,
    $percent15, $percent16, $percent17,
    $percent18, $percent19, $percent110,
    $percent111, $percent112, $percent113,
    $percent114, $percent115, $percent116,
    $percent117, $percent118, $percent119,
    $percent120);
print_r(array_slice($array,0,5));

它的输出是这样的:

Array ( [0] => 36.015505697169 [1] => 2.4181626187962 [2] => 2.4181626187962 [3] => 5.2153134902083 [4] => 100 )

因此,我想弄清楚的是,是否可以按照上面列出的方式打印数组的结果。示例输出如下所示:

Array ( [percent12] => 36.015505697169 [percent13] => 2.4181626187962 [percent14] => 2.4181626187962 [percent15] => 5.2153134902083 [percent16] => 100 )

我觉得这是不可能的,但如果不能,有没有办法分配

[0]=> 36.015505697169 [1]=> 2.4181626187962 

等等来输出其他东西,比如:

[web0]=> 36.015505697169 [web1] => 2.4181626187962

请帮忙!!快把我逼疯了!!

您需要使其成为一个关联数组:

$array=array('percent12' => $percent12, 
             'percent13' => $percent13,
             ...);

我建议使用array_combine()

基本上,您只需要使用键设置新数组,并将当前数组中的值传入,从而在正确的位置创建一个具有所需键的新数组。

像一样尝试

$myArr = array_slice($array,0,5);
$i = 0;
foreach($myArr as $key => $value) {
   $newArr['web'.$i++] = $value;
}
print_r($newArr);