Jump to content

Adding to a multidimensional array


bcfantasy

Recommended Posts

To keep things simple, say this is my starting array:
[code]$players = array('Smith' => array('points' => 100,
                                'assists' => 5,
                                'games' => 10),
                'Jones' => array('points' => 123,
                                'assists' => 7,
                                'games' => 11),
                'Lewis' => array('points' => 86,
                                'assists' => 12,
                                'games' =>8));[/code]
I need to add more categories for each player to reflect their rank in points, assists, and games.  I have been doing this:
[code]uasort($players, "pointssort");
$rank = 1;
$blah = $players;
foreach ($blah as $key => $val) {
    $players[$key]['pointsrank'] = $rank;
    $rank++;
    }[/code]
Is there a better way to get the same result? I don't think I should have to create $blah.
Link to comment
https://forums.phpfreaks.com/topic/26984-adding-to-a-multidimensional-array/
Share on other sites

Try this:
[code]<?php
$players = array('Smith' => array('points' => 100,
                                'assists' => 5,
                                'games' => 10),
                'Jones' => array('points' => 123,
                                'assists' => 7,
                                'games' => 11),
                'Lewis' => array('points' => 86,
                                'assists' => 12,
                                'games' =>8));
 
$rank = 1;
echo '<pre>' . print_r($players,true) . '</pre>'; // debug code
foreach($players as $p => $a)
$players[$p]['pointsrank'] = $rank++;
echo '<pre>' . print_r($players,true) . '</pre>'; // debug code
?>[/code]

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.