views:

109

answers:

3

Hi.. i want to convert this array

 Array
(
    [2] => Array
        (
        )
    [4] => Array
        (
            [12] => Array
                (
                )
            [13] => Array
                (
                 [16] => Array
                    (
                    )
                )
        )
    [5] => Array
        (
        )
    [10] => Array
        (
        )
    [14] => Array
        (
        )
)

into this format

Array
(
    [2] => 2
    [4] => Array
        (
            [0] => 12
            [13] => Array
                (
                    [0] => 16
                )
        )

    [5] => 5
    [10] => 10
    [14] => 14
)

can anybody help? thanks. [continued 16Mar2010]

its not

[2] =>array

but

[2] => 2

if it is an array with 1 child or more, then it would be [4] => Array([12]=>12

input data is

$a = array(2 => array(), 4 => array(12 => array(), 13 => array(16 => array())), 5 => array(), 10 => array(), 14 => array());

A: 
<?php

$arr = array ( "2" => array ( ) , "4" => array ( "12" => array () , 13 => array () , ) , 5 => array () , 10=> array () , 14 => array() );

foreach ( $arr as $key => $val )
{
global $arr ;
if ( empty ( $val ) )
{
  unset($arr[$key]);
  $arr[$key]=$key;
}
}

print_r  ( $arr) ;

?>
pavun_cool
pavon_cool.. nice tips. it is close but can i make 12 and 13 as value not array?
apis17
+5  A: 
foreach($ary as $k => $v)
  $result[$k] = $v ? array_keys($v) : $k;

untested

stereofrog
tested / verified... Works because an empty array is treated as false. If the array has values, it will get `array_keys()` otherwise the key name.
gnarf
thank you stereofrog, this works but i want to add more trees there. let see the updates. thanks for helping.
apis17
can you post your data in a form suitable for testing (no var_dumps, just normal php source code).
stereofrog
the data is $a = array(2 => array(), 4 => array(12 => array(), 13 => array(16 => array())), 5 => array(), 10 => array(), 14 => array());
apis17
+1  A: 
Psytronic
thanks for trying.. :)
apis17
that's what i need to do. thank you. for helping.
apis17
hi psytronic, after revise there is something going wrong. it is [2]=> array but i want [2]=>2, 4=>array because 4 contain additional array. do you know how to fix this?
apis17
ok i've fixed this into $result[$k.'child']
apis17
@apis17 Mine displays [2] => 2 when I print out the results, are you not getting that? And does your other comment mean you have fixed it all now?
Psytronic
yes yes.. already fixed. 1st count the array. if result less than 2 $result[$k] become $value, else $result[$k."_child"] = $k. sorry for late reply.
apis17