0

I have a two dimensional array like this:

Array
(
    [id] => Array
        (
            [0] => 1
        )
    [name] => Array
        (
            [0] => john
        )
    [dept] => Array
        (
            [0] => val_1
            [1] => val_2
        )
    [to] => Array
        (
            [0] => one
            [1] => two
        )
)

Is there anyway I can convert this array to multiple single arrays like the following:

Array
(
    [id] => 1
    [name] => john
    [dept] => val_1
    [to] => one
)
Array
(
    [id] => 1
    [name] => john
    [dept] => val_1
    [to] => two
)
Array
(
    [id] => 1
    [name] => john
    [dept] => val_2
    [to] => one
)
Array
(
    [id] => 1
    [name] => john
    [dept] => val_2
    [to] => two
)

I used array_merge but failed to get what I exactly want. Any help is appreciated

2
  • 2
    i think you should redesign your array structure...this looks really bad Commented Dec 9, 2013 at 20:02
  • Actually, it's one dimensional array, but each inner value is a comma-separated value Commented Dec 9, 2013 at 20:03

3 Answers 3

0

Try this (the solution might not be the cleanest though!):

→ live @ Ideone.com

<?php

$arr = [
    'id' => [
        1
    ],
    'name' => [
        'john'
    ],
    'dept' => [
        'val_1', 'val_2'
    ],
    'to' => [
        'one', 'two'
    ]
];

function convert($arr, $outArrCount) {
    $total = [];
    for ($i=0; $i<$outArrCount; $i++) {
        $entry = [];
        array_walk($arr, function ($val, $key) use (&$entry, $i, $outArrCount) {
            if (count($val) > 1) {
                $entry[$key] = $val[ floor((count($val) / $outArrCount) * $i) ];
            }
            else {
                $entry[$key] = $val;
            }

        });
        $total[] = $entry;
    };
    return $total;
}
var_dump(convert($arr, 4));
Sign up to request clarification or add additional context in comments.

Comments

0

Use this function will help you to restructure you array.

function loopArrayMerger(array $array) {
    if (! $array) {
        return array ();
    }

    return call_user_func_array ( 'array_merge', $array );
}

Comments

0

I've found the following function helpful to answer my question:

function array_cartesian() {
    $_ = func_get_args();
    if(count($_) == 0)
        return array(array());
    $a = array_shift($_);
    $c = call_user_func_array(__FUNCTION__, $_);
    $r = array();
    foreach($a as $v)
        foreach($c as $p)
            $r[] = array_merge(array($v), $p);
    return $r;
}

I can use it as follows:

$cross = array_cartesian(
    $arr[id],
    $arr[name],
    $arr[dept],
    $arr[to]);
print_r($cross);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.