Php 数组\u walk试图写入外部数组
我有一段简单的代码,它没有像我预期的那样工作,请有人解释一下为什么它没有填充字段数组,以及如何解决它Php 数组\u walk试图写入外部数组,php,array-walk,Php,Array Walk,我有一段简单的代码,它没有像我预期的那样工作,请有人解释一下为什么它没有填充字段数组,以及如何解决它 $fields = []; array_walk($class->properties, function($v, $k) use ($fields) { $fields[] = $v->name; }); die(var_dump($fields)); // output is [] 使用以下命令: $fields = []; array_walk($class-
$fields = [];
array_walk($class->properties, function($v, $k) use ($fields) {
$fields[] = $v->name;
});
die(var_dump($fields));
// output is []
使用以下命令:
$fields = [];
array_walk($class->properties, function($v, $k) use (&$fields) {
$fields[] = $v->name;
});
die(var_dump($fields));
在我写了这篇文章之后,我看到了马克·贝克的评论。这是正确的答案
有关参考,请参阅:
数组映射()
:
有关参考,请参阅:
- 以下代码演示了一个类,该类的唯一属性包含一个对象数组,每个对象都有一个name属性,如下所示:
<?php
$class = new stdClass;
$class->properties = [new stdClass,new stdClass, new stdClass];
$class->properties[0]->name = "Anne";
$class->properties[1]->name = "Bob";
$class->properties[2]->name = "Robin";
$fieldsA = [];
$fieldsB = [];
if ( array_walk( $class->properties, function( $o ) use ( &$fieldsA ){
$fieldsA[] = $o->name;
}) ) {
echo "\nMission accomplished:\n";
var_dump($fieldsA);
}
$fieldsB = array_map( function( $e ) {
return $e->name;
},$class->properties);
if (count($fieldsB) > 0) {
echo "\nMission accomplished:\n";
var_dump( $fieldsB );
}
在使用中按引用传递,而不是按值传递:数组_walk($class->properties,function($v,$k)use(&$fields){$fields[]=$v->name;})代码>值得指出的是,对于这个用例,函数array\u map
会是一个更好的选择。带有var\u dump()的die()是免费的。
<?php
$class = new stdClass;
$class->properties = [new stdClass,new stdClass, new stdClass];
$class->properties[0]->name = "Anne";
$class->properties[1]->name = "Bob";
$class->properties[2]->name = "Robin";
$fieldsA = [];
$fieldsB = [];
if ( array_walk( $class->properties, function( $o ) use ( &$fieldsA ){
$fieldsA[] = $o->name;
}) ) {
echo "\nMission accomplished:\n";
var_dump($fieldsA);
}
$fieldsB = array_map( function( $e ) {
return $e->name;
},$class->properties);
if (count($fieldsB) > 0) {
echo "\nMission accomplished:\n";
var_dump( $fieldsB );
}