将元素追加到对象[数组]?

时间:2010-12-31 10:28:09

标签: php

将元素追加到对象[数组]? 我有一个$ A

SimpleXMLElement Object
(
    [books] => Array
    (
        [0] => SimpleXMLElement Object
        (
            [book] => Array
            (
                [0] => SimpleXMLElement Object
                (
                    [info] => SimpleXMLElement Object
                    (
                        [qty] => 12
                        [title] => C++
                    )

                )

                [1] => SimpleXMLElement Object
                (
                    [info] => SimpleXMLElement Object
                    (
                        [qty] => 21
                        [title] => PHP
                    )

                )

            )

        )

        [1] => SimpleXMLElement Object
        (
            [book] => SimpleXMLElement Object
            (
                [info] => SimpleXMLElement Object
                (
                    [qty] => 25
                    [title] => Java
                )

            )

        )

    )

)

我想通过附加[index] => [$ i] [$ j]

返回该新对象
  SimpleXMLElement Object
  (
      [books] => Array
      (
          [0] => SimpleXMLElement Object
          (
              [book] => Array
              (
                  [0] => SimpleXMLElement Object
                  (
                      [info] => SimpleXMLElement Object
                      (
                          [qty] => 12
                          [title] => C++
                          [index]=>[0][0]
                      )

                  )

                  [1] => SimpleXMLElement Object
                  (
                      [info] => SimpleXMLElement Object
                      (
                          [qty] => 21
                          [title] => PHP
                          [index]=>[0][1]
                      )

                  )

              )

          )

          [1] => SimpleXMLElement Object
          (
              [book] => SimpleXMLElement Object
              (
                  [info] => SimpleXMLElement Object
                  (
                      [qty] => 25
                      [title] => Java
                      [index]=>[1][0]
                  )

              )

          )

      )

我试过了:

 foreach($object_xml as $key=> $arr){ //>>>$key =books
      foreach( $arr as $k =>$value){ //$k = book
          foreach($value as $kk=> $val){ //$kk=info
              $val->index = "$key>>>$k>>>$kk";
            //echo '<pre>';
            //print_r($val);
            //echo '</pre>';

          }
        }
    }
/*
    echo '<pre>';
    print_r($object_xml);
    echo '</pre>';
*/
    header('Content-type: text/xml');
    echo $object_xml->saveXml();

1 个答案:

答案 0 :(得分:1)

试试这个

foreach($value as $kk=> $val)
{
  $val->addChild('index', "$key>>>$k>>>$kk");
}