fork download
  1. <?php
  2. $array =
  3. (
  4. '0' => array
  5. (
  6. 'question_id' => 1,
  7. 'question_title' => 'Q1',
  8. 'child_question_id' => NULL
  9. ),
  10.  
  11. '1' => array
  12. (
  13. 'question_id' => 2,
  14. 'question_title' => 'Q2',
  15. 'child_question_id' => NULL
  16. ),
  17.  
  18. '2' => array
  19. (
  20. 'question_id' => 3,
  21. 'question_title' => 'Q3',
  22. 'child_question_id' => 4
  23. ),
  24.  
  25. '3' => array
  26. (
  27. 'question_id' => 3,
  28. 'question_title' => 'Q3',
  29. 'child_question_id' => 5
  30. ),
  31.  
  32. '4' => array
  33. (
  34. 'question_id' => 4,
  35. 'question_title' => 'Q4',
  36. 'child_question_id' => NULL
  37. ),
  38.  
  39. '5' => array
  40. (
  41. 'question_id' => 5,
  42. 'question_title' => 'Q5',
  43. 'child_question_id' => NULL
  44. ),
  45.  
  46. '6' => array
  47. (
  48. 'question_id' => 6,
  49. 'question_title' => 'Q6',
  50. 'child_question_id' => NULL
  51. ),
  52.  
  53. '7' => array
  54. (
  55. 'question_id' => 7,
  56. 'question_title' => 'Q7',
  57. 'child_question_id' => 6
  58. )
  59.  
  60. );
  61.  
  62. $i = 0;
  63. $new = array();
  64. $unsetter = array();
  65. foreach($array as $val)
  66. {
  67. $new[$i] = array();
  68. foreach($val as $key => $data)
  69. {
  70. if(($key == 'child_question_id') && (!is_null($data)))
  71. {
  72. $new[$i]['children'] = array();
  73. $new[$i]['children']['question_id'] = $data;
  74. $new[$i]['children']['question_title'] = $array[$data]['question_title'];
  75. $unsetter[] = $data;
  76.  
  77.  
  78. } else {
  79. $new[$i][$key] = $data;
  80. }
  81. }
  82. $i++;
  83. }
  84. foreach($unsetter as $uns)
  85. {
  86. unset($new[$uns]);
  87. }
  88. $new = array_values($new);
  89. var_dump($new);
Success #stdin #stdout 0.01s 20568KB
stdin
Standard input is empty
stdout
array(5) {
  [0]=>
  array(3) {
    ["question_id"]=>
    int(1)
    ["question_title"]=>
    string(2) "Q1"
    ["child_question_id"]=>
    NULL
  }
  [1]=>
  array(3) {
    ["question_id"]=>
    int(2)
    ["question_title"]=>
    string(2) "Q2"
    ["child_question_id"]=>
    NULL
  }
  [2]=>
  array(3) {
    ["question_id"]=>
    int(3)
    ["question_title"]=>
    string(2) "Q3"
    ["children"]=>
    array(2) {
      ["question_id"]=>
      int(4)
      ["question_title"]=>
      string(2) "Q4"
    }
  }
  [3]=>
  array(3) {
    ["question_id"]=>
    int(3)
    ["question_title"]=>
    string(2) "Q3"
    ["children"]=>
    array(2) {
      ["question_id"]=>
      int(5)
      ["question_title"]=>
      string(2) "Q5"
    }
  }
  [4]=>
  array(3) {
    ["question_id"]=>
    int(7)
    ["question_title"]=>
    string(2) "Q7"
    ["children"]=>
    array(2) {
      ["question_id"]=>
      int(6)
      ["question_title"]=>
      string(2) "Q6"
    }
  }
}