Michał Michał - 1 year ago 59
PHP Question

How looks good structure of construct for creating multidimensial array

I am trying to create constructor which creates an multidimensional array. My result should be like this:-

Checkout my array $result_array

For now I have error: Illegal offset type. Note that I have als use __toString() becose I work on xml data.

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();

Answer Source

You need to change your two foreach() like below:-

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
    }
}

If the above not worked then check this too:-

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
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download