【问题标题】:How can I push an new item to an array which is the result of a method?如何将新项目推送到作为方法结果的数组?
【发布时间】:2017-08-16 06:08:47
【问题描述】:

这是我的代码:

$this->results['twitter'] = array_push($this->twitter($request),"active");

它抛出:

只有变量应该通过引用传递

出了什么问题,我该如何解决?

【问题讨论】:

  • $new_array = $this->twitter($request); $this->results['twitter'] = array_push($new_array,"active");
  • @JYoThI 谢谢。我不能在一行中做到这一点,对吗?
  • 是的,您不能将返回结果作为参数传递。所以你需要将它存储在变量中并作为参数传递。您可以通过引用函数来传递变量,以便函数可以修改变量
  • 你会保存array_push$this->results['twitter']返回的数组长度

标签: php arrays initialization array-push


【解决方案1】:

请注意array_push 返回一个整数,表示加法后数组元素的计数。您可以改用array_merge

$this->results['twitter'] = array_merge($this->twitter($request), ['active']);

【讨论】:

  • 谢谢,点赞。只是订单呢? active 是否总是附加在该数组的末尾?
  • 顺序不应该是相关的..如果您真的需要一种使用该状态的方法,那么只需添加一个键,例如:array_merge($this->twitter($request), ['status' => 'active']).. 之后您可以简单地使用它:@ 987654326@
【解决方案2】:

1st : 将结果存储在变量中然后推送

$new_array = $this->twitter($request);
$this->results['twitter'] = array_push($new_array,"active");

注意:是的,您不能将返回结果作为参数传递。所以你需要将它存储在变量中并作为参数传递。您可以通过引用函数来传递变量,以便函数可以修改变量

【讨论】:

    【解决方案3】:

    也许你想要这样的东西:

    array_push($this->results['twitter'], $this->twitter());

    这会将 twitter() 函数的返回值推送到您的数组中。 请注意,array_push 仅返回包含项目的数量。

    【讨论】:

    • active在哪里?
    • 这取决于你最后需要的数组结构。 $newValue[$this->twitter()] = "active"; array_push($this->results['twitter'], $newValue);
    猜你喜欢
    • 2019-01-08
    • 1970-01-01
    • 2011-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-30
    • 2017-03-26
    • 1970-01-01
    相关资源
    最近更新 更多