0

I'm trying to achieve a nice looking multidimensional array, removing the duplicate keys and having those as a master key with the values as another child array.

This is my starting array:

Array
(
    [0] => Array
        (
            [pa_flavour] => 101
        )

    [1] => Array
        (
            [pa_flavour] => 102
        )

    [2] => Array
        (
            [pa_flavour] => 103
        )

    [3] => Array
        (
            [pa_flavour] => 104
        )

    [4] => Array
        (
            [pa_flavour] => 100
        )

    [5] => Array
        (
            [pa_bottle-size] => 108
        )

    [6] => Array
        (
            [pa_nicotine-strength] => 109
        )

    [7] => Array
        (
            [pa_nicotine-strength] => 110
        )

)

And this is what I'm trying to achieve:

Array
(
    [pa_flavour] => [
        101, 
        102, 
        103,
        104,
        100
    ],
    [pa_bottle-size] => [
        108
    ],
    [pa_nicotine-strength] => [
        109,
        110
    ]
)

I've followed multiple tutorials and used various functions from similar questions, but none of them seem to be working for me. Any ideas?

Thanks in advance.

  • 1
    Possible duplicate of [PHP How to remove duplicate value in multidimensional array and merge others](https://stackoverflow.com/questions/21008192/php-how-to-remove-duplicate-value-in-multidimensional-array-and-merge-others) – Masivuye Cokile May 24 '19 at 11:11
  • @MasivuyeCokile nope, not duplicate. Already tried it. And plus the initial array isn't static, it's populated from database requests, therefore the data is dynamic and wouldn't be able to input the key each time. Cheers. –  May 24 '19 at 11:15
  • Depending on your needs (if you don't require subarrays unless there is more than one row to merge), then [`var_export(array_merge_recursive(...$arr));` is a tidy solution.](https://3v4l.org/JWvGD) – mickmackusa Apr 05 '22 at 08:10

1 Answers1

0

You can approach this as

$res = [];
foreach($arr as $k => $v){
  foreach ($v as $key => $value) {
    $res[$key][] = $value;
  }
}

Live Demo

Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 20