array_walk 未更改值
array_walk not changing value
function values($id,$col)
{
$vals = [1=>['name'=>'Lifting Heavy Boxes']];
return $vals[$id][$col];
}
$complete = [1=>["id"=>"2","sid"=>"35","material_completed"=>"1","date"=>"2017-12-18"]];
$form = 'my_form';
array_walk($complete, function(&$d,$k) use($form) {
$k = values($k, 'name').' ['.date('m/d/y',strtotime($d['date'])).'] ('.$form.')';
echo 'in walk '.$k."\n";
});
print_r($complete);
echo
输出:
in walk Lifting Heavy Boxes [12/18/17] (my_form)
print_r
输出:
Array
(
[1] => Array
(
[id] => 2
[sid] => 35
[material_completed] => 1
[date] => 2017-12-18
)
)
我有另一个非常相似的阵列遍历,效果很好。我能感觉到它们之间的唯一区别是在工作的那个中,值 $d 在它通过遍历之前已经是一个字符串,而在不工作的那个中,$d 是一个数组,它在内部转换为一个字符串步行(成功,但最终失败)。
我缺少什么?
这是固定版本:
array_walk($complete, function(&$d,$k) use($form) {
$d = values($k, 'name').' ['.date('m/d/y',strtotime($d['date'])).'] ('.$form.')';
});
无论如何,这就是我想要做的。我没有尝试更改密钥。我误以为要更改值,您必须将键设置为新值。
您不能在 array_walk()
的回调中更改数组的键:
Only the values of the array
may potentially be changed; its structure cannot be altered, i.e., the programmer cannot add, unset or reorder elements. If the callback does not respect this requirement, the behavior of this function is undefined, and unpredictable.
这个在first comment中也有提到:
It's worth nothing that array_walk can not be used to change keys in the array.
The function may be defined as (&$value, $key) but not (&$value, &$key).
Even though PHP does not complain/warn, it does not modify the key.
function values($id,$col)
{
$vals = [1=>['name'=>'Lifting Heavy Boxes']];
return $vals[$id][$col];
}
$complete = [1=>["id"=>"2","sid"=>"35","material_completed"=>"1","date"=>"2017-12-18"]];
$form = 'my_form';
array_walk($complete, function(&$d,$k) use($form) {
$k = values($k, 'name').' ['.date('m/d/y',strtotime($d['date'])).'] ('.$form.')';
echo 'in walk '.$k."\n";
});
print_r($complete);
echo
输出:
in walk Lifting Heavy Boxes [12/18/17] (my_form)
print_r
输出:
Array
(
[1] => Array
(
[id] => 2
[sid] => 35
[material_completed] => 1
[date] => 2017-12-18
)
)
我有另一个非常相似的阵列遍历,效果很好。我能感觉到它们之间的唯一区别是在工作的那个中,值 $d 在它通过遍历之前已经是一个字符串,而在不工作的那个中,$d 是一个数组,它在内部转换为一个字符串步行(成功,但最终失败)。
我缺少什么?
这是固定版本:
array_walk($complete, function(&$d,$k) use($form) {
$d = values($k, 'name').' ['.date('m/d/y',strtotime($d['date'])).'] ('.$form.')';
});
无论如何,这就是我想要做的。我没有尝试更改密钥。我误以为要更改值,您必须将键设置为新值。
您不能在 array_walk()
的回调中更改数组的键:
Only the values of the
array
may potentially be changed; its structure cannot be altered, i.e., the programmer cannot add, unset or reorder elements. If the callback does not respect this requirement, the behavior of this function is undefined, and unpredictable.
这个在first comment中也有提到:
It's worth nothing that array_walk can not be used to change keys in the array. The function may be defined as (&$value, $key) but not (&$value, &$key). Even though PHP does not complain/warn, it does not modify the key.