如果键相同,如何将值追加到数组中
我有一个关联数组
[name]->user1,
[class_code]->bsc,
[name]->user2,
[class_code]->msc,
[name]->user1,
[class_code]->mca
,现在,我想要结果为
[name]->user1,
[class_code]->bsc,
mca
[name]->user2,
[class_code]->msc
“如果名称相同,则将 class_code 附加到第一个数组”。我该怎么做呢? 我的数组
[1] =stdClass Object
([class_code] =Maths
[userid] =365
[avatar] =default.jpg
[username] =user2
)
[2] =stdClass Object
(
[class_code] =Maths
[userid] = 364
[avatar] =default.jpg
[username] =user1
)
[3] =stdClass Object
(
[class_code] =MCA
[userid] =364
[avatar] =default.jpg
[username] =user1
)
[4] =stdClass Object
(
[class_code] =MCA
[userid] =365
[avatar] =default.jpg
[username] =user2
)
现在是,在显示结果时我想显示前的记录。 user2 as
username:user2
avatar
classcode :MCA,Maths
而不是
username:user2
avatar
classcode :MCA
username:user2
avatar
classcode :Maths
我该怎么做?
I have an associative array as
[name]->user1,
[class_code]->bsc,
[name]->user2,
[class_code]->msc,
[name]->user1,
[class_code]->mca
Now, i want result as
[name]->user1,
[class_code]->bsc,
mca
[name]->user2,
[class_code]->msc
Means if name is same then append the class_code to first one. How should I do that?
My array is
[1] =stdClass Object
([class_code] =Maths
[userid] =365
[avatar] =default.jpg
[username] =user2
)
[2] =stdClass Object
(
[class_code] =Maths
[userid] = 364
[avatar] =default.jpg
[username] =user1
)
[3] =stdClass Object
(
[class_code] =MCA
[userid] =364
[avatar] =default.jpg
[username] =user1
)
[4] =stdClass Object
(
[class_code] =MCA
[userid] =365
[avatar] =default.jpg
[username] =user2
)
Now, while displaying result i want to display records of for ex. user2 as
username:user2
avatar
classcode :MCA,Maths
and not
username:user2
avatar
classcode :MCA
username:user2
avatar
classcode :Maths
how can I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不能有两个值具有相同的键。否则,如果您要求 $myarray['name'],php 将不知道该给您什么。
您可以改用嵌套数组。
例如
或者你可以做这样的事情
You can't have two values with the same key. Otherwise php wouldn't know what to give you if you asked for $myarray['name'].
You could use nested arrays instead.
eg
or you could do something like this
如果你想在那里有两个值,你应该考虑在那里使用一个数组
if you want to have both values in there, you should consider using an array in there
如果
[class_code]
必须包含字符串,你可以尝试if
[class_code]
must contain a string, you can try您可以使整个数组成为多维数组:
检索值:
循环访问值:
You can make the whole array multidimensional:
Retrieving a value:
Cycling through values: