这可能是一个非常简单的问题,很抱歉我缺乏知识,我很愚蠢
将项目添加到阵列后,
$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'
}
如何将值更新为"第二个值"?
您可以直接设置:
foreach ($List as $key => $item)
{
$List[$key]['Text'] = 'Second Value';
}
或参照设置:
foreach ($List as &$item)
{
$item['Text'] = 'Second Value';
}
可能有一种PHP风格的神秘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
通过引用而不是通过值来使用。
foreach ($List as &$item)
{
$item['Text'] = 'Second Value';
}