好的,所以你在做什麼是不正確的開始。
$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
)
試試這個print_r(get_defined_vars()); – Robin
謝謝你的回答!是否有可能只是回聲數組中的值?像回聲$蘋果然後獲得價值? – user3233787
你究竟想在這裏做什麼?你用'fruit'覆蓋'$ fruits'數組中的'$ apple'項目,'$ apple'的值自然會消失嗎?你想要添加項目到數組? – Huey