【发布时间】:2018-10-31 23:07:08
【问题描述】:
我遇到了以下问题:向数组添加数据后,它只存储最后一个插入。
我使用 var_dump 从我的代码中得到以下结果:
array(5) { ["Mount01"]=> string(12) "DebugLevel#0" ["Mount02"]=> string(12) "DebugLevel#0" ["Mount03"]=> string(12) "DebugLevel#0" ["Mount04"]=> string(12) "DebugLevel#0" ["Mount05"]=> string(12) "DebugLevel#0" }
所以它只保存我做的最后一个输入。但我想要这样:
array(X) { ["Mount01"]=> string(XX) "DebugLevel#0" ["Mount01"]=> string(XX) "Bla#5" ["Mount02"]=> string(XX) "DebugLevel#0" ["Mount02"]=> string(XX) "Bla#5" }
这是我的 XML 结构:
<Config>
<Core>
<Store>
<Mount01>
<DebugLevel>0</DebugLevel>
<Bla>5</Bla>
<Mount02>
<DebugLevel>0</DebugLevel>
<Bla>5</Bla>
这是我的代码:
class Storage{
public static function get_storage_data()
{
if(file_exists('/var/www/content/data/data.xml')) :
$xml = simplexml_load_file('/var/www/content/data/data.xml');
foreach ($xml->Core->Store as $mounts) {
foreach ($mounts as $mount) {
foreach ($mount->Children() as $value) {
$store[$mount->getName()]=$value->getName()."#".$value;
}
}
}
var_dump($store);
else:
write_log(sprintf("data.xml not found"));
endif;
}
那么,我怎样才能达到我想要的输出呢?也欢迎代码改进。
【问题讨论】:
-
一个数组只能有一个具有任何给定名称的键,所以“我怎样才能实现我想要的输出”的简单答案是“你不能”,对不起。您需要提出一种不同的格式,不要尝试为同一个键提供两个不同的值。
-
好的,所以这里最好的方法是找到更好的格式。因此,如果我执行 $array['mount01'] = $data['bla#5', 'bla2#6'] 之类的操作,它应该可以做到。所以我可以从字面上做 array_push($data,'bla#5') 并在内循环结束时 $array['mount01']=$data?我从未听说将数组存储为值是一种不好的方法?我知道您可以在 C 中使用“结构”,但由于 php 没有它们,所以并不容易。
-
知道了,感谢@IMSoP 的提示!