在2x2多维数组中添加其他关联数组但保留密钥

时间:2014-10-08 00:25:48

标签: php arrays multidimensional-array

Howdie do,

我有一个服务器类型的多维关联数组。该数组包含一个子数组值。

更容易看到:

$servers = array('Dell R410 Dual Xeon X5650 Hexacore 2.66 GHz' => array('Model' =>$R410Model, 'Description' =>$R410Desc,'Counter' => $R410HexCoreE5650Count));

我想添加其他服务器类型关联数组。这就是我所做的:

$servers[] = array('Atoms D510 1.66Ghz' => array('Model' =>$AtomModel, 'Description' =>$AtomDesc,'Counter' => $AtomCount));

$servers[] = array('Celerons 2.40Ghz' => array('Model' =>$CeleronModel, 'Description' =>$CeleronDesc,'Counter' => $CELERONCount));

它确实添加了值,但它是通过索引而不是实际的服务器类型键来实现的。

Array ( [Dell R410 Dual Xeon X5650 Hexacore 2.66 GHz] => Array ( [Model] => DELL R410 [Description] => Dual Xeon X5650 Hexacore 2.66 GHz [Counter] => 25 ) 

[0] => Array ( [Atoms D510 1.66Ghz] => Array ( [Model] => ATOM [Description] => D510 1.66Ghz [Counter] => 1 ) ) 

[1] => Array ( [Celerons 2.40Ghz] => Array ( [Model] => [Description] => [Counter] => 0 ) ) )

如何将子数组向上移动一个,以便按键而不是索引添加它们。所以它看起来像这样

 Array ( [Dell R410 Dual Xeon X5650 Hexacore 2.66 GHz] => Array ( [Model] => DELL R410 [Description] => Dual Xeon X5650 Hexacore 2.66 GHz [Counter] => 25 ) 

 Array ( [Atoms D510 1.66Ghz] => Array ( [Model] => ATOM [Description] => D510 1.66Ghz [Counter] => 1 ) ) 

 Array ( [Celerons 2.40Ghz] => Array ( [Model] => [Description] => [Counter] => 0 ) ) )

1 个答案:

答案 0 :(得分:2)

我只是为你解答,因为这是一个简单的错字。

您想要做的是:

而不是使用整数索引($server[] = array(....)创建数组对象。
$servers['Atoms D510 1.66Ghz'] = array('Model' =>$AtomModel, 'Description' =>$AtomDesc,'Counter' => $AtomCount);
$servers['Celerons 2.40Ghz'] = array('Model' =>$CeleronModel, 'Description' =>$CeleronDesc,'Counter' => $CELERONCount);