-2

I have an array that looks like this:

Array
(
    [0] => Array
        (
            [594576] => 604329
        )

    [1] => Array
        (
            [594576] => 594577
        )

)

And I would like to order it grouping by its key as the title says and adding the key as value too and part of the new order, this is how the array should look in the end

Array
(
    [0] => Array
        (
            [0] => 594576
            [1] => 604329
            [2] => 594577
        )

)

Making the key as the first value, I have tried this without success looking info here on SO in questions like this

Group array values based on key in php?

But this didn't help me, I'm not expert using PHP and I hope you can help me to achieve this or guide me about how I need to do first, thank you.

Ashe
  • 187
  • 1
  • 13
  • StackOverflow expects you to [try to solve your own problem first](http://meta.stackoverflow.com/questions/261592). Please update your question to show what you have already tried in a [mcve]. For further information, please see [ask], and take the [tour] :) – Barmar Mar 08 '18 at 18:18
  • You can use `array_keys($element)[0]` to get the first key in each array element. – Barmar Mar 08 '18 at 18:18
  • Why do you need to get as a result an array in another array? – DamiToma Mar 08 '18 at 18:19
  • I find this question to be generally **Unclear** because the sample input is too small and lacks enough data to verify correct answers from incorrect answers. It basically wants to loop the subarrays then remove the duplicates, but what if a value matches a key? should the value get purged as if it was a duplicate key? When does it looks like with different keys in the input data? – mickmackusa Apr 25 '21 at 00:55

1 Answers1

0

Use RecursiveIteratorIterator and RecursiveArrayIterator. Then array_unique the result to remove duplicate values.

$array = [
    [
        594576 => 604329
        ],
        [
        594576 => 594577
        ],
    ];

$result = [];

foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $k => $v)
{
    $result[] = $k;
    $result[] = $v;
}

var_dump(array_unique($result));

The output:

array(3) {
  [0]=>
  int(594576)
  [1]=>
  int(604329)
  [3]=>
  int(594577)
}
Kevin Kopf
  • 13,327
  • 14
  • 49
  • 66