0

假设我需要三个阵列,福特、雪佛兰和道奇。每个数组包含三个项目:

$ford['engine'] = 'something';
$ford['color'] = 'something';
$ford['price'] = 'something';

$chevy['engine'] = 'something';
$chevy['color'] = 'something';
$chevy['price'] = 'something';

$dodge['engine'] = 'something';
$dodge['color'] = 'something';
$dodge['price'] = 'something';

我可以把它写出来没问题,而且不需要太长时间。但是,假设我需要制作五十或六十个阵列,所有阵列都有十到二十个不同的项目。我想在每个数组文件的顶部放置一个变量来表示数组名称,但我对语法不太清楚,我不太熟悉 $$ 或者我如何将它与数组一起使用:

$name = 'ford';

$(I want this to be "$name")['engine'] = 'something';
$(I want this to be "$name")['color'] = 'something';
$(I want this to be "$name")['price'] = 'something';

我也考虑过这样做:

$name = 'ford';

$view[$name.'_engine'] 
$view[$name.'_color'] 
$view[$name.'_price'] 

我可以就解决此问题的最佳方法获得一些建议吗?

4

2 回答 2

5

写一个小函数来做到这一点

$cars = array(); //Create an array to hold the values    
function writeArray($car, $var1, $var2, $var3) {
     global $cars;
     $cars[$car] = array('engine' =>  $var1, 'color' => $var2, 'price' => $var2);
}
//Now use it like
writeArray('Chevy', $something, $something, $something);

//If you want to access the array in the form of $ford['engine'] then use this

extract($cars); //This will split the array into small array accessible by model 
于 2012-04-03T23:45:01.157 回答
4

您可以使用变量变量

$var = 'ford';
$$var['engine'] = '...';
$$var['color'] = '...';

$var = 'chevy';
$$var['engine'] = '...';
$$var['color'] = '...';

或者只使用多维数组:

$cars = array();

$make = 'ford';
$cars[$make] = array();
$cars[$make]['engine'] = '...';
$cars[$make]['color'] = '...';

// or

$cars['ford'] = array(
    'engine' => '...',
    'color' => '...',
);
于 2012-04-03T23:45:09.217 回答