phparraysrecursion

Recursively replace empty arrays with their key


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

Solution

  • function refactor($a){
      $result = array();
      foreach($a as $k => $v)
        $result[$k] = (is_array($v) && count($v) > 0) ? refactor($v) : $k;
      return $result;
    }

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

    Sorry, didn't see that you wanted the internal array not to have the keys and values as the same.

    EDIT: After you updated your question, I edited my function to do what you need:

    function refactor($a, $rootNode = false){
      $result = array();
      foreach($a as $k => $v){
          if($rootNode){
              $result[$k] = (is_array($v) && count($v) > 0) ? refactor($v) : $k;
          }else{
              $result[] = (is_array($v) && count($v) > 0) ? refactor($v) : $k;      
          }
      }
      return $result;
    }
    
    $a = array(2 => array(), 4 => array(12 => array(), 13 => array(16 => array())), 5 => array(), 10 => array(), 14 => array());
    print_r($a);
    $b = refactor($a, true);
    print_r($b);