D
D
Dmitry2016-10-29 13:45:14
PHP
Dmitry, 2016-10-29 13:45:14

How to quickly rebuild an array?

Hello!
There is an array:

array(2) {
  [0]=>
  array(1) {
    ["019a6eab-8fa8-11e6-a509-005056c00008"]=>
    array(3) {
      [0]=>
      string(3) "one"
      [1]=>
      string(4) "two"
      [2]=>
      string(9) "three"
    }
  }
  [1]=>
  array(1) {
    ["22d4bccb-8fa8-11e6-a509-005056c00008"]=>
    array(1) {
      [0]=>
      string(10) "four"
    }
  }
}

It needs to be rebuilt to look like this:
array(2) {
  ["019a6eab-8fa8-11e6-a509-005056c00008"]=>
  array(3) {
    [0]=>
    string(3) "one"
    [1]=>
    string(4) "two"
    [2]=>
    string(9) "three"
  }
  ["22d4bccb-8fa8-11e6-a509-005056c00008"]=>
  array(1) {
    [0]=>
    string(10) "four"
  }
}

It is clear that you can rebuild the array, but this option is not suitable.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mikhail Osher, 2016-10-29
@miraage

<?php

$input = [
    [
        'guid-1' => [
            'one',
            'two',
            'three',
        ],
    ],
    [
        'guid-2' => [
            'four',
        ],
    ],
];

var_dump(
    array_reduce(
        $input,
        function ($acc, $item) {
            foreach ($item as $guid => $values) {
                $acc[$guid] = $values;
            }

            return $acc;
        },
        []
    )
);

array(2) {
  ["guid-1"]=>
  array(3) {
    [0]=>
    string(3) "one"
    [1]=>
    string(3) "two"
    [2]=>
    string(5) "three"
  }
  ["guid-2"]=>
  array(1) {
    [0]=>
    string(4) "four"
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question