简体   繁体   中英

How to loop multi dimensional array to get values

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');
    }
}

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;
}

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,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM