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

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

Add Key and Value to a multidimesnsion array PHP

问题

我有以下多维数组

array (
  'count' => 386,
  'report' =>
  array (
    'uuid' => '183a3956-9425-43da-845c-2839c30a951b',
    'name' => 'OnlyScrumFND',
    'Have' =>
    array (
      0 =>
      array (
        'uuid' => '00ad6013-4109-4940-a711-4f8fb5389e8c',
      ),
      1 =>
      array (
        'uuid' => 'd651a86d-beac-498a-85a0-75ce62f28f4e',
      ),
    ),
  ),
)

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

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

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

英文:

I have the following multidimenson array

array (
  'count' => 386,
  'report' => 
  array (
    'uuid' => '183a3956-9425-43da-845c-2839c30a951b',
    'name' => 'OnlyScrumFND',
    'Have' => 
    array (
      0 => 
      array (
        'uuid' => '00ad6013-4109-4940-a711-4f8fb5389e8c',
      ),
      1 => 
      array (
        'uuid' => 'd651a86d-beac-498a-85a0-75ce62f28f4e',
      ),
    ),
  ),
)

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

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

But it is not woking, Any hint? thanks rob

答案1

得分: 0

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

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

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

以下是实现:

你可以在这里查看

英文:

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

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

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:

确定