1

I have this multi-dimensional array and I'm trying to convert it into array given below

Array
(
    [id] => Array
        (
            [0] => 1
            [1] => 3
        )
    [team_id] => Array
        (
            [0] => 654868479
            [1] => 463733228
        )
    [seed] => Array
        (
            [0] => 1
            [1] => 2
        )
)

I want following result

Array
(
    [0] => Array
        (
            [id] => 1
            [team_id] => 654868479
            [seed] => 1
        )
    [1] => Array
        (
            [id] => 3
            [team_id] => 463733228
            [seed] => 3
        )
)

Here is what I have achieved so far. I actually want $seeded[] array is the same format as it is required to submit update_batch. Which will ultimately update database records.

$seeds = $this->input->post();
$i=0;
foreach ($seeds as $key => $value){
    if(!empty($key) && !empty($value)){
        for($i=0; $i=5; $i++) {
            $seeded[] = array(
                'id' => (id go here),
                'tournament_id' => $tournament_id,
                'stage_id' => $stage_id,
                'seed_id' => (seed go here),
                'team_name' => (team_id go here),
            );
        }
        $this->db->update_batch('tournament_seed', $seeded, 'id');
    }
}

2 Answers 2

2

Iterate the array and convert it using below code.

$seeded= array();
for($i =0; $i < count($seeds['id']); $i++){
    $tempArr['id'] = $seeds['id'][$i];
    $tempArr['team_id'] = $seeds['team_id'][$i];
    $tempArr['seed'] = $seeds['seed'][$i];
    $seeded[] = $tempArr;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Please quote your indexes, they will be read as PHP constants (in future versions of PHP), which will be undefined.
Undefined variable: arr
Assign old array to $arr or use your old array name
0

I've written a function that will allow you to transform any array of similar structure to what you have above, to an array of the form you are looking for.

You can build your array in this way:

$arr = [
    'id'      => [1, 3],
    'team_id' => [654868479, 463733228],
    'seed'    => [1, 2],
];

function array_flatten($arr) {
    $res = [];
    foreach($arr as $id => $valuesArray) {
        foreach($valuesArray as $index => $value)
            $res[$index][$id] = $value;
    }
    return $res;
}

print_r(array_flatten($arr));

Hope this helps,

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.