title: PHP flatten a Multidimensional Array with keys
body: <p>I wrote some PHP code to line up the children of an array. I wrote a recursive function.</p>
  <p>Everything is listed correctly one below the other, but some arrays do not have the &quot;Name&quot; key.</p>
  <p>Does anyone have any idea how I can get it to show everyone's &quot;Name&quot; key?</p>
  <p>My PHP Code:</p>
  <pre><code>$json = '[
      {
          &quot;name&quot;: &quot;A&quot;,
          &quot;children&quot;: [
              {
                  &quot;name&quot;: &quot;B&quot;,
                  &quot;children&quot;: [
                      {
                          &quot;name&quot;: &quot;C&quot;
                      },
                      {
                          &quot;name&quot;: &quot;D&quot;,
                          &quot;children&quot;: [
                              {
                                  &quot;name&quot;: &quot;E&quot;
                              },
                              {
                                  &quot;name&quot;: &quot;F&quot;
                              }
                          ]
                      }
                  ]
              },
              {
                  &quot;name&quot;: &quot;G&quot;
              }
          ]
      },
      {
          &quot;name&quot;: &quot;H&quot;
      }
  ]';
  
  
  header('Content-Type: application/json; charset=utf-8');
  $json = json_decode($json, true);
  
  function array_flatten($array, $prefix = '') {
      $return = array();
      foreach ($array as $key =&gt; $value) {
          if (is_array($value) &amp;&amp; array_key_exists(&quot;children&quot;, $value)){
              $return = array_merge($return, array_flatten($value, $key));
          }else if (is_array($value) &amp;&amp; count($value) &gt; 1){
              foreach ($value as $keyA =&gt; $valueA) {
                  if (is_array($valueA) &amp;&amp; array_key_exists(&quot;children&quot;, $valueA)){
                      $return = array_merge($return, array_flatten($valueA, $keyA));
                  }else{
                      $return[] = $valueA;
                  }
              }
          } else {
              $return[] = $value;
          }
      }
  
      return $return;
  }
  
  echo json_encode(array_flatten($json));
  </code></pre>
  <p>Current Result:</p>
  <pre><code> [&quot;A&quot;,&quot;B&quot;,{&quot;name&quot;:&quot;C&quot;},&quot;D&quot;,{&quot;name&quot;:&quot;E&quot;},{&quot;name&quot;:&quot;F&quot;},{&quot;name&quot;:&quot;G&quot;},{&quot;name&quot;:&quot;H&quot;}]
  </code></pre>
  <p>What I want:</p>
  <pre><code>[{&quot;name&quot;:&quot;A&quot;},{&quot;name&quot;:&quot;B&quot;},{&quot;name&quot;:&quot;C&quot;},{&quot;name&quot;:&quot;D&quot;},{&quot;name&quot;:&quot;E&quot;},{&quot;name&quot;:&quot;F&quot;},{&quot;name&quot;:&quot;G&quot;},{&quot;name&quot;:&quot;H&quot;}]
  </code></pre>