M
M
Mikhail Shatilov2014-03-19 21:28:51
PHP
Mikhail Shatilov, 2014-03-19 21:28:51

What is the best way to change the structure of an array in php?

How to most elegantly convert an array of the form:

[data] => Array
(
    [1] => Array
        (
            [text] => Array
                (
                    [0] => link1
                    [1] => link2
                )

            [active] => Array
                (
                    [0] => 1
                    [1] => 1
                )

            [id] => Array
                (
                    [0] => 0
                    [1] => 0
                )
        )
)

into an array like:
[data] => Array
(
    [1] => Array
        (
            [0] => Array
                (
                    [text] => link1
                    [active] => 1
                    [id] => 0
                )
            [1] => Array
                (
                    [text] => link2
                    [active] => 1
                    [id] => 0
                )
        )
)

Part already figured out:
$keys = array();
foreach ($data as $item) {
  $keys = array_fill_keys(array_keys($item),(object)array());
  // ...
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Tyranron, 2014-03-19
@iproger

function zip($tuple_of_lists)
{
    $list_of_tuples = array();
    foreach($tuple_of_lists as $key => $list) {
        foreach($list as $i => $value) {
            $list_of_tuples[$i][$key] = $value;
        }
    }
    return $list_of_tuples;
}

$data = array_map('zip', $data);

try here

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question