Home>
Array A
0 =>array: 4 [▼
    0 =>"testUser-1"
    1 =>"Search for Leads"
    2 =>"Inflow route"
]
1 =>array: 4 [▼
    0 =>"testUser-2"
    1 =>"Search for Leads"
    2 =>"Inflow route"
]
2 =>array: 4 [▼
    0 =>"testUser-3"
    1 =>"Search for Leads"
    2 =>"Inflow route"
]
Array B
0 =>array: 2 [▼
    0 =>"testUser-1"
    1 =>"Target title-1"
]
1 =>array: 2 [▼
    0 =>"testUser-2"
    1 =>"Target title-2"
]

If there are two arrays as shown above, is it possible to store only the difference of array B as an additional element to array A?
I'd like to try various things in the loop and get it as below, but it's not working. Any professor will be saved.

Array A
0 =>array: 4 [▼
    0 =>"testUser-1"
    1 =>"Search for Leads"
    2 =>"Inflow route"
    3 =>"Target title-1"
]
1 =>array: 4 [▼
    0 =>"testUser-2"
    1 =>"Search for Leads"
    2 =>"Inflow route"
    3 =>"Target title-2"
]
2 =>array: 4 [▼
    0 =>"testUser-3"
    1 =>"Search for Leads"
    2 =>"Inflow route"
]
php
  • Answer # 1

    Is it like this?

    $a = [
      ["testUser-1", "Lead search", "Inflow route"],
      ["testUser-2", "Lead search", "Inflow route"],
      ["testUser-3", "Lead search", "Inflow route"],
    ];
    $b = [
      ["testUser-1", "Target title-1"],
      ["testUser-2", "Target title-2"],
      ];
    foreach ($a as&$x) {
      $z = array_filter ($b, function ($y) use ($x) {return $x [0] == $y [0];});
      array_walk ($z, function ($y) use (&$x) {$x [] = $y [1];});
    }
    print_r ($a);

  • Answer # 2

    I think there is a better way

    <? php
        $a = [
            0 =>[
                0 =>"testUser-1",
                1 =>"Search for leads",
                2 =>"Inflow route",
            ],
            1 =>[
                0 =>"testUser-2",
                1 =>"Search for leads",
                2 =>"Inflow route",
            ],
            2 =>[
                0 =>"testUser-3",
                1 =>"Search for leads",
                2 =>"Inflow route",
            ],
        ];
        $b = [
            0 =>[
                0 =>"testUser-1",
                1 =>"Target title-1",
            ],
            1 =>[
                0 =>"testUser-2",
                1 =>"Target title-2",
            ],
        ];
        $keys = array_unique (array_merge (array_keys ($a), array_keys ($b)));
        $c = [];
        $d = [];
        foreach ($keys as $key) {
            $c [$key] = array_unique (array_merge ($a [$key] ?? [], $b [$key] ?? []));
            $d [$key] = array_merge ($a [$key] ?? [], array_diff ($b [$key] ?? [], $a [$key] ?? []));
        }
        var_dump ($c);
        var_dump ($d);

Related articles