【问题标题】:How looks good structure of construct for creating multidimensial array用于创建多维数组的构造结构看起来如何
【发布时间】:2018-01-02 19:22:50
【问题描述】:

我正在尝试创建创建多维数组的构造函数。我的结果应该是这样的:-

Checkout my array $result_array

现在我有错误:非法偏移类型。请注意,我也使用 __toString() 因为我处理 xml 数据。

class Property {

    public $xmlClass;
    public $elemClass = '';
    public $first_array = array();
    public $result_array = array();
    public $data = '';
    public $data2 = '';

    public function __construct($xml, $elem) {
        $this->xmlClass = $xml;
        $this->elemClass = $elem;

        foreach ($xml->xpath('//*[@baza]') as $val) {
            $this->first_array[] = $val;
            foreach ($val->ksiazka as $value) {
                $data = $value->$elem->__toString();
                $this->result_array[$this->first_array][] = $data;
            }
        }
    }

    public function getResult() {
        return $this->result_array;
    }

}

$result_autor = new Property($xml, 'autor');
$autor = $result_autor->getResult();

【问题讨论】:

    标签: php xml foreach constructor


    【解决方案1】:

    您需要更改您的两个foreach(),如下所示:-

    foreach($xml->xpath('//*[@baza]') as $val) {
        //$this->first_array[] = $val; not needed
        foreach($val->ksiazka as $key=> $value){ //check $key here
          $data = $value->$elem->__toString();
          $this->result_array[$key][] = $data; // add $key hear
        }
    }
    

    如果上述方法不起作用,请也检查一下:-

    foreach($xml->xpath('//*[@baza]') as $key=> $val) { //check $key here
        //$this->first_array[] = $val; not needed
        foreach($val->ksiazka as $value){ 
          $data = $value->$elem->__toString();
          $this->result_array[$key][] = $data; // add $key hear
        }
    }
    

    【讨论】:

    • 就是这样!非常感谢您提供这两个示例。我仍在学习它是如何工作的。
    • @Michał 很高兴为您提供帮助 :):)
    猜你喜欢
    • 2023-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-10
    • 2016-07-28
    • 2019-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多