将现有数组添加到3d数组

时间:2012-09-06 12:46:53

标签: php arrays

我正在尝试构建一个3d php数组,最终以xml的形式输出......这是我试图用来证明这个概念的代码......

$test = array('apple','orange');
$results = Array(
  'success' => '1',
  'error_number' => '',
  'error_message' => '',
  'results' => Array (
       'number_of_reports' => mysql_num_rows($run),
       'item' => $test
   )
);

我希望结果数组看起来像

<success>1</success>
<error_number/>
<error_message/>
<results>
     <number_of_reports>18</number_of_reports>
     <item>
         <0>apple</0>
         <1>orange</1>
     </item>
</results>

实际上,苹果和橙色阵列本身就是一个3d ...如果你曾经使用过ebay api ......你会知道我想要做什么(我认为)

2 个答案:

答案 0 :(得分:2)

试一试:

代码:

<?php
$test = array('apple','orange');
$results = Array(
  'success' => '1',
  'error_number' => '',
  'error_message' => '',
  'results' => Array (
       'number_of_reports' => 1,
       'item' => $test
   )
);

print_r($results);
function addChild1($xml, $item, $clave)
{
    if(is_array($item)){
        $tempNode = $xml->addChild($clave,'');
        foreach ($item as $a => $b)
        {
            addChild1($tempNode, $b, $a);
        }           
    } else {
        $xml->addChild("$clave", "$item");
    }
}

$xml = new SimpleXMLElement('<root/>');
addChild1($xml, $results,'data');
$ret = $xml->asXML();

print $ret;

输出:

<?xml version="1.0"?>
<root><data><success>1</success><error_number></error_number><error_message></error_message><results><number_of_reports>1</number_of_reports><item><0>apple</0><1>orange</1></item></results></data></root>

答案 1 :(得分:0)

见下面的网址。我认为它非常适合你: -

How to convert array to SimpleXML

或尝试一下: -

$xml = new SimpleXMLElement('<root/>');
array_walk_recursive($test_array, array ($xml, 'addChild'));
print $xml->asXML();