laravel 数组推送另一个数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16643480/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Array push another array
提问by 1myb
The following is the current array return from database via eloquent of laravel. I want to push something into the array and may i know how to?
以下是通过laravel的eloquent从数据库返回的当前数组。我想将一些东西推入数组,我可以知道如何做吗?
The data in the return
返回中的数据
Company Object (
[attributes] => Array (
[id] => 1
[company_name] => superman
[company_fullname] => Superman Ent. )
[original] => Array (
[id] => 1
[company_name] => superman
[company_fullname] => Superman Ent. )
[relationships] => Array ( )
[exists] => 1
[includes] => Array ( ) )
while i can call this via foreach the array and access by {{ $x->company_name }}. I want to extend the array with some custom information like, total member count?
虽然我可以通过 foreach 数组调用它并通过 {{ $x->company_name }} 访问。我想用一些自定义信息来扩展数组,比如成员总数?
I tried in this way and failed.
我以这种方式尝试并失败了。
$temp = array("count" => "1232");
array_push($companyInfo, $temp);
I got this
我懂了
array_push() expects parameter 1 to be array, object given
array_push() 期望参数 1 是数组,给定的对象
UpdateThe companyInfo array is return by laravel, and due to my foolish & careless (few days sleepless night +_+) i didn't notice everything is inside ['attributes']! The data can be access by the follow after applied methods from the answer.
更新companyInfo 数组是由 laravel 返回的,由于我的愚蠢和粗心(几天不眠之夜 +_+),我没有注意到 ['attributes'] 中的所有内容!数据可以通过以下方法访问答案中的应用方法。
{{ $x['attributes']['company_name'] }}
{{ $x[0]['count'] }}
回答by Maxim Kumpan
$CompanyInfo in your case is an object. You need to either specify a named parameter to save your $temp array info:
$CompanyInfo 在您的情况下是一个对象。您需要指定一个命名参数来保存您的 $temp 数组信息:
$temp = array("count" => "1232");
$companyInfo->temp = $temp;
Or cast the object into an array:
或者将对象转换为数组:
$temp = array("count" => "1232");
$companyInfo = (array) $companyInfo;
array_push($companyInfo, $temp);
回答by RDK
Try do it with out function array_push:
尝试不使用函数 array_push 来实现:
$temp = array("count" => "1232");
$temp[] = $companyInfo;
or
或者
$temp = array("count" => "1232");
$temp['companyInfo'] = $companyInfo;
$temp['companyInfo']->getSomeData();
回答by Amar Gharat
You have got array_push error because you passed an object instead of an array.
您有 array_push 错误,因为您传递的是对象而不是数组。
You're almost right just do following changes,
你几乎是对的,只需做以下更改,
$companyInfo = (array)$companyInfo;
array_push($companyInfo, $temp);