在PHP中向多维数组添加键和值。

huangapple go评论101阅读模式
英文:

Add Key and Value to a multidimesnsion array PHP

问题

我有以下多维数组

  1. array (
  2. 'count' => 386,
  3. 'report' =>
  4. array (
  5. 'uuid' => '183a3956-9425-43da-845c-2839c30a951b',
  6. 'name' => 'OnlyScrumFND',
  7. 'Have' =>
  8. array (
  9. 0 =>
  10. array (
  11. 'uuid' => '00ad6013-4109-4940-a711-4f8fb5389e8c',
  12. ),
  13. 1 =>
  14. array (
  15. 'uuid' => 'd651a86d-beac-498a-85a0-75ce62f28f4e',
  16. ),
  17. ),
  18. ),
  19. )

我想在数组的子级中添加一些信息

  1. foreach ($OUTPUT AS &$have['report']['Have']) {
  2. $have['name'] = "something";
  3. }

但它不起作用,有什么提示吗?谢谢 rob

英文:

I have the following multidimenson array

  1. array (
  2. 'count' => 386,
  3. 'report' =>
  4. array (
  5. 'uuid' => '183a3956-9425-43da-845c-2839c30a951b',
  6. 'name' => 'OnlyScrumFND',
  7. 'Have' =>
  8. array (
  9. 0 =>
  10. array (
  11. 'uuid' => '00ad6013-4109-4940-a711-4f8fb5389e8c',
  12. ),
  13. 1 =>
  14. array (
  15. 'uuid' => 'd651a86d-beac-498a-85a0-75ce62f28f4e',
  16. ),
  17. ),
  18. ),
  19. )

I would like to add some info to the Array in a sublevel

  1. foreach ($OUTPUT AS &$have['report']['Have']) {
  2. $have['name'] = "something";
  3. }

But it is not woking, Any hint? thanks rob

答案1

得分: 0

你已经非常接近了。你可以尝试以下解决方案。

  1. foreach ($OUTPUT['report']['Have'] as &$item) {
  2. $item['name'] = "something";
  3. }

在这里,我使用&运算符来修改foreach循环中的原始数组元素,而不是复制的元素。

以下是实现:

你可以在这里查看

英文:

You are very close. you can try with following solution.

  1. foreach ($OUTPUT['report']['Have'] as &$item) {
  2. $item['name'] = "something";
  3. }

I am using & operator here to modify the original array element in foreach loop instead of copied one.

Find the implementation below .

you can check here

huangapple
  • 本文由 发表于 2023年2月8日 23:54:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75388371.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定