在 PHP 中构建动态数组
我需要使用使用不同格式/结构的对象创建一个数组
:
$t = object()
$t > user = object()
$t > user > 0 (object) name = 'wilson';
$t > user > 0 (object) first = 'carl';
我需要得到:
$t = array(
name = wilson
first name = phil
这是我尝试过的以及我陷入困境的地方
foreach($t as $a) {
foreach($a as $l) {
$arr[$l->0->name] = $l->0->first; // line 10
}
}
print_r($arr);
现在我收到错误:
PHP 解析错误:语法错误,意外的 T_LNUMBER,期待 homework1-a-1.php 中的 T_STRING 或 T_VARIABLE 或 '{' 或 '$' 第 10 行
我能做些什么来修复它?
I need to create an array using a object using different format/structure
I have:
$t = object()
$t > user = object()
$t > user > 0 (object) name = 'wilson';
$t > user > 0 (object) first = 'carl';
I need to get:
$t = array(
name = wilson
first name = phil
Here's what I tried and where I'm stuck
foreach($t as $a) {
foreach($a as $l) {
$arr[$l->0->name] = $l->0->first; // line 10
}
}
print_r($arr);
Now I get an error:
PHP Parse error: syntax error, unexpected T_LNUMBER, expecting
T_STRING or T_VARIABLE or '{' or '$' in homework1-a-1.php on
line 10
What can I do to fix it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你的问题令人困惑。这就是我的理解:
您有以下内容:
$t
,它是一个对象。$t->user
,也是一个对象。$t->user[0]->name = 'wilson'
$t->user[0]->first = 'carl'
你说你需要得到:
$t->name = 'wilson'
$t->first = 'carl'
你在问题中说“phil”,但是给定对象
$t
没有引用“phil”,所以我不知道“phil”是否凭空出现,或者什么。这是对问题的正确看法吗?如果是这样,您需要在问题中澄清这一点。说
$t >用户> 0(对象)名称
没有任何意义。抱歉,这是一个“答案”,我只是无法在评论中包含所有这些内容。如果你澄清问题我会删除它。希望我不是唯一对此感到困惑的人。
Your question is confusing. This is what I understand:
You have the following:
$t
, which is an object.$t->user
, also an object.$t->user[0]->name = 'wilson'
$t->user[0]->first = 'carl'
You say you need to get:
$t->name = 'wilson'
$t->first = 'carl'
You say 'phil' in the question, but the given object
$t
has no reference to a 'phil' so I don't know if 'phil' appears out of thin air, or what.Is this a correct view of the problem? If so, you need to clarify this in the question. saying
$t > user > 0 (object) name
makes no sense.Sorry this is an "answer", I just couldn't fit all of this in a comment. I will delete it if you clarify the question. Hopefully I am not the only person confused by this.
这不是有效的 PHP 代码。如果您希望
$t
采用您显示的格式,只需执行以下操作:现在
$t
是一个数组,键为'name'
和 <代码>'名字'。你的 foreach 循环没有任何意义。
$t
是两个字符串的数组。循环它只会给出值'wilson'
和'phil'
。编辑:假设
$t
已给您,那么您的 for 循环应如下所示:您不能执行
$l->0
。您需要将0
包装在{}
中。$l->{0}
。This is not valid PHP code. If you want
$t
in the format you show, just do this:Now
$t
is an array, with keys'name'
and'first name'
.Your foreach loop doesn't make any sense.
$t
is an array of two strings. Looping over it will just give the values'wilson'
and'phil'
.EDIT: Assuming
$t
was given to you, then your for loop should look like this:You can't do
$l->0
. You need to wrap the0
in{}
.$l->{0}
.