简体   繁体   中英

How to access values of a multidimensional associative array

I have an array called $scores which has an index called 'team' which itself is an array with indices 'w', 'l' and 'd'. How do I access the values of 'w', 'l' and 'd'?

I have tried:

echo '<td>' . $scores['team']['w'] . '</td>';
echo '<td>' . $scores['team']['l'] . '</td>';
echo '<td>' . $scores['team']['d'] . '</td>';

and

echo '<td>' . array_values(array_keys($scores['team'], 'w')) . '</td>';
echo '<td>' . array_values(array_keys($scores['team'], 'l')) . '</td>';
echo '<td>' . array_values(array_keys($scores['team'], 'd')) . '</td>';

But these do not work.

declaring the array:

$scores = array (
                            'team' => array (
                                                'w'     => 0
                                            ,   'l'     => 0
                                            ,   'd'     => 0
                                            )
                    );

print_r($scores):

Array ( [team] => Array ( [w] => 0 [l] => 0 [d] => 0 ) [team one] => Array ( [l] => 2 [w] => 1 [d] => 1 ) [team two] => Array ( [w] => 1 [l] => 1 [d] => 1 ) [team three] => Array ( [l] => 1 ) [team four] => Array ( [w] => 1 ) [team five] => Array ( [w] => 1 ) )

This is now solved - thankyou to contributors.

The problem was I was trying to access the value from within a for loop:

for($i = 0; $i < count($teams); $i++)
{
    echo '<td>' . $scores[$teams[$i]]['l'] . '</td>';
}

This gave me the answer I was looking for.

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