在PHP中将多个值附加到关联数组

时间:2014-05-30 14:51:24

标签: php arrays associative-array

我想创建一个最终看起来像这样的PHP数组:

idPlayer  namePlayer Points
1             John     20
2             Sam      25
3             Ben      22

但我想一次追加价值:

  • 首先添加idPlayer和namePlayer
  • 然后为该idPlayer附加点数(我每次循环时都会使用$ idPlayer变量)

我怎么能在PHP中这样做? 我在想:

$myArray['idPlayer'] = "1";
$myArray['namePlayer'] = "John";
$myArray['Points'] = "20"

然后,我怎么告诉数组进入下一行?

3 个答案:

答案 0 :(得分:0)

使用idPlayer作为索引:

$players = [
    1 => [
        'namePlayer' => 'John',
        'points' => 20,
    ],
    5 => [
        'namePlayer' => 'Seth',
        'points' => 25,
    ],
    13 => [
        'namePlayer' => 'Ben',
        'points' => 35,
    ],
];

var_dump($players);

http://codepad.viper-7.com/nSXmZF

在php< 5.4中使用array()而不是[]构造函数。

答案 1 :(得分:0)

// output array
$myArray = array();

// your loop
while (something) {

  // make an array for this iteration
  $itarr = array();

  // put stuff in it
  $itarr['idPlayer'] = "1";
  $itarr['namePlayer'] = "John";
  $itarr['Points'] = "20"

  // append it to output array using standard array indexing
  $myArray[] = $itarr;
  // OR, your own index
  $myArray[$itarr['idPlayer']] = $itarr;

}

答案 2 :(得分:0)

我不知道你为什么想要达到这样的目的。但请考虑这个例子:

// like player table array initial
$players = array(
    array(
        'idPlayer' => 1,
        'namePlayer' => 'John',
    ),
    array(
        'idPlayer' => 2,
        'namePlayer' => 'Sam',
    ),
    array(
        'idPlayer' => 3,
        'namePlayer' => 'Ben',
    ),
);


// data points to be added later (like points table)
$points = array(
    array(
        'idPlayer' => 1,
        'Points' => 20,
    ),
    array(
        'idPlayer' => 2,
        'Points' => 25,
    ),
    array(
        'idPlayer' => 3,
        'Points' => 22,
    ),
);

$myArray = array();
foreach($players as $key => $value) {
    foreach($points as $index => $element) {
        // if this particular id matches the record inside points table then merge
        if($value['idPlayer'] == $element['idPlayer']) {
            $myArray[] = array('idPlayer' => $value['idPlayer'], 'namePlayer' => $value['namePlayer'], 'Points' => $element['Points']);
        }
    }
}

应该输出如下内容:(可以在表格数据中使用)

Array
(
    [0] => Array
        (
            [idPlayer] => 1
            [namePlayer] => John
            [Points] => 20
        )

    [1] => Array
        (
            [idPlayer] => 2
            [namePlayer] => Sam
            [Points] => 25
        )

    [2] => Array
        (
            [idPlayer] => 3
            [namePlayer] => Ben
            [Points] => 22
        )

)