匹配值后替换php数组

fzsnzjdm  于 2021-09-29  发布在  Java
关注(0)|答案(2)|浏览(501)

我有一个基本数组,如下所示

  1. $orgigal = [
  2. 0 => [
  3. 'month' => '02',
  4. 'total_sum_coin' => 0,
  5. ],
  6. 1 => [
  7. 'month' => '03',
  8. 'total_sum_coin' => 0,
  9. ],
  10. 2 => [
  11. 'month' => '04',
  12. 'total_sum_coin' => 0,
  13. ],
  14. ]

还有另一个替换阵列,如下所示

  1. $replace = [
  2. 0 => [
  3. 'month' => '03',
  4. 'total_sum_coin' => 10,
  5. ],
  6. 1 => [
  7. 'month' => '04',
  8. 'total_sum_coin' => 20,
  9. ],
  10. ]

使用后更换功能

  1. array_replace($orgigal,$replace)

它被键替换了,我试着在和几个月的比赛后用值替换它。
我的欲望输出

  1. $orgigal = [
  2. 0 => [
  3. 'month' => '02',
  4. 'total_sum_coin' => 0,
  5. ],
  6. 1 => [
  7. 'month' => '03',
  8. 'total_sum_coin' => 10,
  9. ],
  10. 2 => [
  11. 'month' => '04',
  12. 'total_sum_coin' => 20,
  13. ],
  14. ]
mbjcgjjk

mbjcgjjk1#

取代 month 它必须是唯一的,因此只需对其进行索引并替换:

  1. $orgigal = array_replace(array_column($orgigal, null, 'month'),
  2. array_column($replace, null, 'month'));

或:

  1. $orgigal = array_column($replace, null, 'month') + array_column($orgigal, null, 'month');

如果你不想 month 作为后键,则只需使用 array_values .

q35jwt9p

q35jwt9p2#

如果可以稍微更改数组结构,可以使用array\u merge而不是array\u replace。否则,您可以简单地使用+数组union运算符,但请记住,要像replace+original一样进行求和,因为重复的键将从与merge相同的页面的第1个运算符示例中获取:

  1. <?php
  2. $array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');
  3. $array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b');
  4. $result = $array1 + $array2;
  5. var_dump($result);
  6. ?>

这导致:

  1. array(5) {
  2. [0]=>
  3. string(6) "zero_a"
  4. [2]=>
  5. string(5) "two_a"
  6. [3]=>
  7. string(7) "three_a"
  8. [1]=>
  9. string(5) "one_b"
  10. [4]=>
  11. string(6) "four_b"
  12. }
展开查看全部

相关问题