【问题标题】:XML Data to multidimensional ArrayXML 数据到多维数组
【发布时间】: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 的提示!

标签: php arrays simplexml


【解决方案1】:
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) {
            $data=[];
            foreach ($mount->Children() as $value) {
              array_push($data,[$value->getName()."#".$value]);
            }
            $store[$mount->getName()]=$data;
          }
        }
    else:
        write_log(sprintf("data.xml not found"));
    endif;
  }

回答我的问题。

【讨论】:

    猜你喜欢
    • 2019-02-27
    • 2012-02-14
    • 2017-04-11
    • 2016-12-07
    • 2011-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多