2012-02-10 24 views
0

这可能是很简单的问题,我的缺乏knwoledge的,和我的愚蠢对不起...更新值

将项目添加到阵列后,

$List[1] = array(
    'Id' => 1, 
    'Text'=> 'First Value' 
); 

我需要改变内数组中的项的值,

foreach ($List as $item) 
{ 
    $item['Text'] = 'Second Value'; 
} 

但是当我检查值保持相同

foreach ($List as $item) 
{ 
    echo $item['Text']; //prints 'First Value' 
} 

如何将值更新为'Second Value'?

+0

这将改变整个数组元素,而不仅仅是一个项目。 – 2012-02-10 03:27:15

回答

2

您可以直接设置它:

foreach ($List as $key => $item) 
{ 
    $List[$key]['Text'] = 'Second Value'; 
} 

或引用设置:

foreach ($List as &$item) 
{ 
    $item['Text'] = 'Second Value'; 
} 
1

可能有一种PHP-ish神秘的Perl方式来访问该值,但我发现它更简单地遍历数组并直接设置值。

for($i = 0; $i < count($List); $i++) 
{ 
    $List[$i] = 'Second Value'; 
} 

编辑:好奇心越来越好。 http://www.php.net/manual/en/control-structures.foreach.php

foreach($List as &$item) 
{ 
    $item = 'Second Value'; 
} 

通知这导致$item为通过引用而不是由值所使用的&

1
foreach ($List as &$item) 
{ 
    $item['Text'] = 'Second Value'; 
}