简体   繁体   中英

Display some arrays and multidimensional arrays together

Here are the variables:

$ids = array_unique($_POST['id']);
$total_ids = count($ids);

$name = $_POST['name'];

$positions = $_POST['position'];
$total_positions = count($positions);

This is what the print_r shows:

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

[name] => Array ( 
    [0] => George 
    [1] => Barack ) 

[position] => Array ( 
    [1] => Array ( 
        [0] => 01 
        [1] => 01 ) 
    [2] => Array ( 
        [0] => 01 
        [1] => 01 
        [2] => 01 ) )

This is the result which I would like to get on refresh/submit:

[id][0];
    [name][0];
        [position][1][0];[position][1][1]
[id][1];
    [name][1];
        [position][2][0];[position][2][1];[position][2][2]

To make the wanted result well clear:

User with [id][0] 
    is called [name][0] 
        and works at [position][1][0];[position][1][1]
BUT

User with [id][1]
    is called [name][1];
        and works at [position][2][0];[position][2][1];[position][2][2]

Please note that [position] s starts with [1] , not [0] .

How could I display the arrays in the order I showed?

I'm not 100% sure I understand what you need, but to try to match the final-example of the output you displayed I came up with the following:

// iterate through each of the `$ids` as a "user"
foreach ($ids as $key => $value) {
    // output the user's ID
    echo 'User with ' . $value;
    if (isset($name[$key])) {
        // output the user's name
        echo ' is called ' . $name[$key];
    }
    if (isset($position[$key + 1])) {
        // output a ';'-delimited list of "positions"
        echo ' and works at ';
        $positions = '';
        // the `$positions` array starts with index 1, not 0
        foreach ($position[$key + 1] as $pos) {
            $positions .= (($positions != '') ? ';' : '') . $pos;
        }
        echo $positions;
    }
    echo '<br />';
}

This will give output similar to:

User with 1 is called Bill and works at pos1;pos2;pos3
User with 14 is called Jill and works at pos134

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