无法在php中获取嵌套数组的节点键名

无法在php中获取嵌套数组的节点键名

问题描述:

I am trying to display nested array, and it prints whole array but unable to print node element like in our example [destinations],[QUOTATIONS]. i want to print array with this node elements.

actually i am generating tree view using this nested element that why i need to display node element also.

stdClass Object
(
    [id] => 148
    [status] => I
    [consname] => juned  ansari
    [consusername] => junedconsultant
    [agency_name] => mayur
    [agency_username] => MayurMaroliya
    [destinations] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 260
                    [from_date] => 2016-11-24
                    [to_date] => 2016-11-29
                    [country_id] => IN
                    [QUOTATIONS] => Array
                        (
                              [id] => 260
                              [name] => ABC  
                        )

                )

        )

)

here is my recursion code.

<?php
function traverseArray($array)
{
    // Loops through each element. If element again is array, function is recalled. If not, result is echoed.
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            traverseArray($value);
        } else {
            if (gettype($value) == 'object') {
                echo "<ul>";
                traverseArray($value);
            } else {
                echo '<li><a href="#">' . $key . " : " . $value . '</a>';
            }
        }
    }
}
traverseArray($transition_data);

我正在尝试显示嵌套数组,它打印整个数组但无法打印节点元素,如我们的示例中所示[ 目的地],[QUOTATIONS]。 i想要用这个节点元素打印数组。 p>

实际上我正在使用这个嵌套元素生成树视图,这也是我需要显示节点元素的原因。 / p>

  stdClass Object 
(
 [id] =&gt; 148 
 [status] =&gt; I 
 [consname] =&gt; juned ansari 
 [consusername  ] =&gt; junedconsultant 
 [agency_name] =&gt; mayur 
 [agency_username] =&gt; MayurMaroliya 
 [destinations] =&gt;数组
(
 [0] =&gt; stdClass对象
(
  [id] =&gt; 260 
 [from_date] =&gt; 2016-11-24 
 [to_date] =&gt; 2016-11-29 
 [country_id] =&gt; IN 
 [QUOTATIONS] =&gt; 数组
(
 [id] =&gt; 260 
  [name] =&gt;  ABC 
)
 
)
 
)
 
)
  code>  pre> 
 
 

这是我的递归代码。 p>

 &lt;?php 
function traverseArray($ array)
 {
 //循环遍历每个元素。 如果element又是数组,则调用函数。 如果没有,结果将被回显。
 
 \ foreach($ array as $ key =&gt; $ value){
 if(is_array($ value)){
 \ traverseArray($ value); 
} else {
 if  (gettype($ value)=='object'){
 echo“&lt; ul&gt;”; 
 \ traverseArray($ value); 
} else {
 echo'&lt; li&gt;&lt; a href =“  #“&GT;”  。  $ key。  “:”。  $ value。  '&lt; / a&gt;'; 
} 
} 
} 
} 
 
 \ traverseArray($ transition_data); 
  code>  pre> 
  div>

You can print node element in if block of you array checking. like:

if (is_array($value)) {
            echo $key;//this will print the nodes(destinations,QUOTATIONS) .you cal add ul here
            traverseArray($value);
        }