2015-07-19 36 views
0

我對這個初學者問題感到抱歉。我的問題是我想獲得數組中分配的變量名的值。例如像這樣:PHP數組賦值然後得到變量值

$fruits = array($apple, $mango, $banana); 

然後我分配數組中的元素相同的值。

for ($i = 0; $i < count($fruits); $i++) { 
    $fruits[$i] = "fruit"; 
} 

當我要打印數組中的蘋果價值,我會做:

echo $fruits[0]; 

但我想要的是用於打印數組中蘋果的價值:

echo $apple; 

我該怎麼做?對不起初學者在這裏..

+0

試試這個print_r(get_defined_vars()); – Robin

+0

謝謝你的回答!是否有可能只是回聲數組中的值?像回聲$蘋果然後獲得價值? – user3233787

+1

你究竟想在這裏做什麼?你用'fruit'覆蓋'$ fruits'數組中的'$ apple'項目,'$ apple'的值自然會消失嗎?你想要添加項目到數組? – Huey

回答

0

好的,所以你在做什麼是不正確的開始。

$apple = "apple"; 
$mango = "mango"; 
$banana ="banana"; 

$fruits = array($apple, $mango, $banana); 

for ($i = 0; $i < count($fruits); $i++) { 
    $fruits[$i] = "fruit"; 
} 
echo "<pre>"; 
print_r($fruits); 

你在for循環中做了什麼就是重寫數組的值。所以,當你做的print_r您將獲得:

Array 
(
    [0] => fruit 
    [1] => fruit 
    [2] => fruit 
) 

如果你想存儲無論是水果或蔬菜(我不知道如果是這種情況,因爲您的數組名稱是「水果」),但如果你想做到這一點,那麼你應該使用關聯數組:當你希望看到什麼樣的東西,蘋果是

$cabbage= 'cabbage'; 
$stuffIEat = array($apple => 'fruit', 
        $mango => 'fruit', 
        $banana =>'fruit', 
        $cabbage => 'vegetable'); 

現在,你這樣做:

echo $stuffIEat[$apple]; //prints fruit 
echo $stuffIEat[$cabbage]; //prints vegetable 

現在如果你想打印你吃的所有水果,喲ü做:

print_r(array_keys($stuffIEat,'fruit'));

這將打印

Array 
(
    [0] => apple 
    [1] => mango 
    [2] => banana 
) 
1

這是一個另類。

<?php 
$fruits = array(
    "apple" => $apple, 
    "mango" => $mango, 
    "banana" => $banana); 
foreach ($fruits as $key => $value) { 
    $fruits[$key] = "fruit"; 
} 

echo $fruits['mango'];