Note that there are some explanatory texts on larger screens.

plurals
  1. POFlatten a nested PHP hierarchal array into string representations
    primarykey
    data
    text
    <p>Given an array:</p> <pre><code>0 =&gt; ( [parent_id] =&gt; null, [name] =&gt; "Root" [children] =&gt; array( 10 =&gt; array( [parent_id] =&gt; 0, [name] =&gt; "Category A", [children] =&gt; array( 30 =&gt; array( [parent_id] =&gt; 10, [name] =&gt; "Category C" ) ) ), 20 =&gt; array( [parent_id] =&gt; 0, [name] =&gt; "Category B" ) ) ) </code></pre> <p>I need to return an array of string representations of those paths...</p> <pre><code>array( [0] =&gt; "Root", [10] =&gt; "Root &gt; Category A", [30] =&gt; "Root &gt; Category A &gt; Category C", [20] =&gt; "Root &gt; Category B" ) </code></pre> <p>I've been messing around doing this recursively but I'm having some trouble doing it efficiently. Are there simple ways to do this that I'm just overlooking?</p> <p><strong>EDIT:</strong></p> <p>Solution is simply a slightly modified version of Alexander Varwijk's answer. A few tweaks to handle non-existent children, calling the function recursively via <strong>FUNCTION</strong> constant so it's easy to change the function name and a change from array_merge to the + operator to combine the arrays in order to preserve keys.</p> <pre><code>function flatten($data, $prefix = "", $item_seperator = "/") { $seperator = $prefix == "" ? "" : $item_seperator; $return = array(); if (is_array($data)) { foreach($data as $key =&gt; $value) { $return[$value["endeca_id"]] = $prefix . $seperator . $value["url_key"]; if(array_key_exists("children", $value)) { $return = $return + call_user_func(__FUNCTION__, $value["children"], $prefix . $seperator . $value["url_key"], $item_seperator); } } } return $return; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload