通过方法将字符串和数组值作为类属性累积到数组中
我有一个类,其方法 add() 接受字符串和数组。我需要一个包含所有用户的数组,但我似乎无法得到它。我得到的只是包含所有用户的多个数组。我怎样才能将这些数组合并为一个?
class Users {
function add($stringOrArray) {
$arr = array();
if(is_array($stringOrArray)) {
$arr = $stringOrArray;
} else if(is_string($stringOrArray)) {
$arr[] = $stringOrArray;
} else {
echo('errrrror');
}
print_r($arr);
}
当我使用此测试时:
public function testOne() {
$users = new Users();
$users->add('Terrell Irving');
$users->add('Magdalen Sara Tanner');
$users->add('Chad Niles');
$users->add(['Mervin Spearing', 'Dean Willoughby', 'David Prescott']);
这就是我得到的,多个数组,但我需要一个数组。
Array
(
[0] => Terrell Irving
)
Array
(
[0] => Magdalen Sara Tanner
)
Array
(
[0] => Chad Niles
)
Array
(
[0] => Mervin Spearing
[1] => Dean Willoughby
[2] => David Prescott
)
I have a class with method add() that accepts strings and arrays. I need to have an array with all users, but I cannot seem to get it. All I get is multiple arrays with all users. How could I merge those arrays into one?
class Users {
function add($stringOrArray) {
$arr = array();
if(is_array($stringOrArray)) {
$arr = $stringOrArray;
} else if(is_string($stringOrArray)) {
$arr[] = $stringOrArray;
} else {
echo('errrrror');
}
print_r($arr);
}
When I use this test:
public function testOne() {
$users = new Users();
$users->add('Terrell Irving');
$users->add('Magdalen Sara Tanner');
$users->add('Chad Niles');
$users->add(['Mervin Spearing', 'Dean Willoughby', 'David Prescott']);
This is what I get, multiple arrays but I need one array.
Array
(
[0] => Terrell Irving
)
Array
(
[0] => Magdalen Sara Tanner
)
Array
(
[0] => Chad Niles
)
Array
(
[0] => Mervin Spearing
[1] => Dean Willoughby
[2] => David Prescott
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你可以从你的方法中减少很多不必要的膨胀。
您可以将所有传入数据显式转换为
数组
类型。这会将字符串转换为包含单个元素的数组。如果变量已经是数组,则值不会发生任何变化。使用展开运算符 (
...
) 将变量推送到类属性中。代码:(演示)
输出:
You can cut a lot of unnecessary bloat from your method.
You can cast ALL incoming data to
array
type explicitly. This will convert a string into an array containing a single element. If the variable is already an array, nothing will change about the value.Use the spread operator (
...
) to perform a variadic push into the class property.Code: (Demo)
Output:
您所需要的只是将添加的用户存储到类属性中,例如
$listOfUsers
。如果添加数组,则使用 array_merge() 函数,否则只需在索引数组的末尾添加新用户即可。
在您的示例中,您将数据本地存储在方法
add()
中,并且不会保留以供将来使用。使用类属性 $listOfUsers 可以更正此行为,可以在类对象内使用$this->listOfUsers
访问该属性,如果需要,也可以在类外部使用该属性进行访问。All you need is to store the added users in a class property, for example
$listOfUsers
.If adding the array you use the array_merge() function otherwise just add new user at the end of indexed array.
In your example you are storing the data locally within the method
add()
and it is not kept for future usage. This behavior is corrected using the class property $listOfUsers that can be accesed using$this->listOfUsers
within the class object and if needed outside of the class.